大网数据广告活动
服务器运维问答

nginx redirect directory including php files

· 52CE 我爱测

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/ …

问题原文

原帖链接 · imthebest · CC BY-SA 3.0

Previously my site URLs were like this:

Now the URLs are like this:

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
%

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-12-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。