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

nginx rewrite if query string exists

· 52CE 我爱测

In the past a project was getting moved from / to /subdir . As the old URL structure was something like /index.php?foo/123/bar I used the following rewrite to get everything to /forum : rewrite ^\/index\.php(.*)$ /forum/$1 last; …

问题原文

原帖链接 · KittMedia · CC BY-SA 4.0

In the past a project was getting moved from / to /subdir. As the old URL structure was something like /index.php?foo/123/bar I used the following rewrite to get everything to /forum:

rewrite ^\/index\.php(.*)$ /forum/$1 last;

The problem with this rewrite is that it also redirects / to /forum/ and /index.php to /forum/. Now I want to not redirect them because there has been created a new start page in /.

So / should not be redirected but if there is a query string it should.

I tried the following:

location / {
        if ($query_string !~ "") {
                rewrite ^\/index\.php(.*)$ /forum/$1 last;
        }

        try_files $uri $uri/ @rewrite;
}

The start page works now but if there is a query string nothing gets rewritten and I don’t know why.

已采纳解答

原帖链接 · KittMedia · CC BY-SA 4.0

After half a day of silence I figured it out. By using the full $request_uri outside the location block and an adjustment to the regex to make any character after the index.php mandatory it works fine:

location / {
    try_files $uri $uri/ @rewrite;
}

if ($request_uri ~* "^\/index\.php(.+)$") {
    rewrite ^(.*)$ /forum/$1 last;
}

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

资料来源与适用范围

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

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

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