Nginx rewrite triggers download

2019-05-25 04:00发布

I'm struggling with creating a simple rewrite url on nginx.
My configuration looks like this:

location /foo/bar {
    rewrite ^/(.+)$ /index.php?p=$1 break;
}

E.g. /foo/bar/baz should become /foo/bar/index.php?p=baz (internally of course)

However, everything accessed through /foo/bar/ triggers a download of an index.php located at the root. How do I get this to work ?

I've also tried using try_files but can't figure out how to exclude the /foo/bar/ path from $uri.

标签: nginx rewrite
2条回答
姐就是有狂的资本
2楼-- · 2019-05-25 04:34

Change

rewrite ^/(.+)$ /index.php?p=$1 break;

to

rewrite ^/(.+)$ /index.php?p=$1 last;

Based on http://wiki.nginx.org/HttpRewriteModule#rewrite,

last - completes processing of current rewrite directives and restarts the process (including rewriting) with a search for a match on the URI from all available locations.

[Edit] Using break will stay inside the same location block. In your case, there is no other rules inside that location block. So by default, nginx will serve that as a file request.

查看更多
仙女界的扛把子
3楼-- · 2019-05-25 04:37

The PHP file isn't interpreted and treated as a regular file. You will need to setup a CGI server like FPM and pass the connection to those processes.

See http://wiki.nginx.org/Configuration for details

UPDATE

I'm not sure why your example breaks. But my guess is you'll need to change the rewrite into a try_files.

location /foo/bar {
    try_files $uri $uri/ /index.php?p=$uri;
}
查看更多
登录 后发表回答