Nginx & PHP in a subdirectory
I have an app behind nginx. But i need a specific path in this app redirect to a Wordpress Blog
Example :
example.com/ -------> Redirect to my app
example.com/whatever/ -------> Redirect to my app too
example.com/blog/ ------->Redirect to my Wordpress Blog
So, I add a location matching this sub-path
server {
listen 80 default_server;
index index.php;
server_name _;
location ^~ /blog {
root /path/to/my/blog;
index index.php index.html;
location ^~ /blog/(.*\.php)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /path/to/my/blog/$fastcgi_script_name;
include fastcgi_params;
}
}
location ~* /(.*) {
#here the conf for the rest of the website
}
}
And when i try to get the page, i have a 404 with this eror in the logs :
2016/05/22 15:27:24 [error] 21759#0: *1 open() "/path/to/my/blog/blog/index.php" failed (2: No such file or directory), client: XX.XX.XX.XX, server: _, request: "GET /blog/index.php HTTP/1.1", host: "example.com"
With /blog is duplicate.
How i can fix this ?
EDIT :
Now i have this (Thanks to Richard Smith) :
location ^~ /blog {
root /path/to/my/;
index index.php;
try_files $uri $uri/ /blog/index.php;
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
}
}
But now, i got index.php event if i try to ge another file (toto.html for example)
If i replace
try_files $uri $uri/ /blog/index.php;
with
try_files $uri $uri/;
I got a 404 with
2016/05/22 20:57:21 [error] 22621#0: *1 "/path/to/my/blog/toto.html/index.php" is not found (20: Not a directory), client: 84.98.248.33, server: _, request: "GET /blog/toto.html/ HTTP/1.1", host: "example.com"
in the logs
EDIT 2 :
The file exist and currently, and i give it 777 rights (i will remove them later before go to production):
drwxrwxrwx 2 user group 4096 May 22 20:36 .
drwxr-xr-x 11 user group 4096 May 23 06:20 ..
-rwxrwxrwx 1 user group 126 May 22 13:30 index.php
-rwxrwxrwx 1 user group 102 May 22 10:25 old.index.html
-rwxrwxrwx 1 user group 12 May 22 12:24 toto.html
Thank you fo your patience !
As /blog
is the first component of the URI, you need to remove it from the root
. Use root /path/to/my
when inside location ^~ /blog
.
See this document for details.
Also, your .php
location is invalid syntax. You can use something like this:
location ^~ /blog {
root /path/to/my;
index index.php;
try_files $uri $uri/ /blog/index.php;
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
}
}
See this document for details.
Finally, the rest of the website can use normal locations, such as location /
as the ^~
modifier on your location ^~ /blog
gives it precedence for any URI beginning with /blog
. See my second reference for details.