问题原文
原帖链接 · imthebest · CC BY-SA 3.0
Previously my site URLs were like this:
- https://www.example.com/forums/threads/test.123/ (type 1)
- https://www.example.com/forums/showthread.php?t=123 (type 2)
Now the URLs are like this:
- https://www.example.com/threads/test.123/ (type 1)
- https://www.example.com/showthread.php?t=123 (type 2)
I'm using the following:
location /forums/ {
rewrite ^/forums/(.*)$ https://www.example.com/$1 permanent;
}
And it properly redirects the URLs of type 1, however URLs like type 2 are returning 404. How can I make nginx to also redirect the php files? Thanks!
已采纳解答
原帖链接 · cnst · CC BY-SA 3.0
The reason you're having this issue is because location directives that are defined by regular expressions take precedence and have the final word, hence, you probably have your location ~ \.php$ handler process the request.
As per http://nginx.org/r/location, what you should do is simply add the ^~ modifier to your existing code, to not check regular expressions, like so:
location ^~ /forums/ {
rewrite ^/forums/(.*)$ https://www.example.com/$1 permanent;
}
Another consideration is that although $uri (the variable that's behind the location and rewrite directives) does not contain $is_args$args (and, hence, $1 in the example above doesn't, either), they'll still be added automatically in the rewrite context, as per http://nginx.org/r/rewrite, so, nothing else needs to be done to the code above.
As a bonus, a maintenance-related optimisation is still possible — namely, you don't actually have to specify https (or $scheme) and the host explicitly, but can let nginx figure it out based on the context.
Also, as explained at http://nginx.org/docs/http/ngx_http_rewrite_module.html#internals, you can save an extra instruction by making / be part of the capture.
As such, with the above two optimisations, the best approach to your situation may then be:
location ^~ /forums/ {
rewrite ^/forums(/.*)$ $1 permanent;
}
Here's the above code at work, which confirms that $scheme://$host (and :$server_port, only if needed), are automatically added, subject to the settings described at http://nginx.org/r/absolute_redirect:
% curl -i "localhost:4441/forums/showthread.php?t=123" |& fgrep Location
Location: http://localhost:4441/showthread.php?t=123
%
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
