Nginx rewrite in subfolder (404)

我是研究僧i 提交于 2019-12-02 19:19:45
ereckers

The accepted answer routes everything through index.php.
This will break certain script includes, the wp-admin script being one of them.

You can use:

location /blog/ {
    index index.php;
    try_files $uri $uri/ /blog/index.php?$args;
}

Um... Thank you for all comments and answer. But finally I use this method to get it works

location /blog {
    index index.php;
    rewrite ^/blog/(.*)+$ /blog/index.php?$1; # it finally works
    # return 200 $request_uri; # it is for inspect what $request_uri is
    # try_files $uri $uri/ /blog/index.php$request_uri$is_args$args; # it gets 500 server error
}

Please point out if current setting has any problems. thank you!

I would suggest the following, to catch any permalinks under subfolder /blog

location /blog {
    index index.php;
    try_files $uri $uri/ /blog/index.php?$args;
}

Try this, I changed my answer to try to imitate the same behaviour you are using in your rewrite.

location ~ /blog(.*) {
    index index.php;
    try_files $uri /blog/index.php?$1&$args;
}

Think for php, rewrite is no needed with something like this:

location /app/ {
  include fastcgi_params;
  fastcgi_param  SCRIPT_FILENAME /path/to/your/app/index.php;
  fastcgi_pass php;
}

With following fastcgi pass

upstream php {
    server unix:/var/run/php5-fpm.sock;
}

Try this

location /api {
    # example: http://demo.com/api/channels/dmzb
    root   /data/webserver/demo.com/api/web;
    rewrite ^/api/(.*) /$1 break;
    try_files $uri $uri/ /api/index.php?$args;

    location ~ ^/api/index\.php {
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;

        # fix request_uri
        set $changed_request_uri $request_uri;
        if ($changed_request_uri ~ ^/api(.*)) {
            set $changed_request_uri $1;
        }
        fastcgi_param REQUEST_URI $changed_request_uri;

        # fix script_filename
        fastcgi_split_path_info ^(?:\/api\/)(.+\.php)(.*);
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

A universal solution for pretty URLs in root and one subfolder level:

set $virtualdir "";
set $realdir "";

if ($request_uri ~ ^/([^/]*)/.*$ ) {
        set $virtualdir /$1;
}

if (-d "$document_root$virtualdir") {
        set $realdir "${virtualdir}";
}

location / {
        try_files $uri $uri/ $realdir/index.php?$args;
}

I found that with permalink enabled, I needed a combination of both sets of answers given here, otherwise

  1. With only the rewrite, none of the static files got served
  2. With only the try files, the permalinks did not work

This is working on my set up

location /blog/ {
      rewrite ^/blog/(blog/(tag|category|20??)/.*)+$ /blog/index.php?$1;
      try_files $uri $uri/ /blog/index.php?$args =404;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!