Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving php files from different locations in nginx

I have my main website and wordpress in different directories on my server on which I use nginx as the web server. The main website is in /home/me/www and Wordpress is in /home/me/wordpress. I need to have them in separate directories this way for a particular reason. How do I specify this in the nginx configuration file? I currently have the following and it does not work:

location / {
    root   /home/me/www;
    index  index.php index.html index.htm;
}

location /blog {
    root /home/me/wordpress;
    index index.php index.html index.htm;
}

location ~ \.php$ {
    set $php_root /home/me/www;
    if ($request_uri ~ /blog) {
        set $php_root /home/me/wordpress;
    }
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $php_root$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}

It currently returns HTTP 404 when I try to access http://mydomain/blog

like image 444
ErJab Avatar asked Feb 10 '10 13:02

ErJab


People also ask

Can Nginx serve PHP files?

Create a PHP page in NginxAfter the restart, PHP is fully enabled on Nginx. To prove this, create a PHP file in Nginx's /var/www/html folder and test to ensure the page renders properly on the server. This creates the most basic PHP file outside of a “Hello World” example you could create.

Can Nginx have multiple servers?

There is, in theory, no limit to the number of sites that you can host on your VPS with Apache or Nginx.

How does Nginx match location?

To find a location match for an URI, NGINX first scans the locations that is defined using the prefix strings (without regular expression). Thereafter, the location with regular expressions are checked in order of their declaration in the configuration file.


2 Answers

Check out this question and the Nginx Manual.

Try changing your blog line to:

location ^~ /blog/ {
    root /home/me/wordpress;
    index index.php index.html index.htm;
}
like image 185
Nick Presta Avatar answered Sep 20 '22 02:09

Nick Presta


I struggled with this for hours now and finally reached the working configurations as the following:

location /php-app {
    passenger_enabled off;
    alias /path/to/php-app/$1;
    index index.php index.html;
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^/php-app(.*)$ /index.php?q=$1 last;
}

location ~ \.php$ {
    alias /path/to/php-app/$1;
    rewrite ^/php-app(.*)$ $1 last;
    passenger_enabled off;
    fastcgi_pass unix:/tmp/php-fpm.socket;
    fastcgi_index index.php;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /path/to/php-app$fastcgi_script_name;
    fastcgi_intercept_errors on;
}
like image 42
minniux Avatar answered Sep 19 '22 02:09

minniux