我正在为传递给 index.php 的 url 参数进行一些 Nginx 重写:
- 老的:
?topic=10126.msg36887
- 新的:
?posts/36887/
我的两个问题:
1)我如何重写新的参数结构,因为它使用“参数/值/”而不是传统的“参数=值”结构?
2)我的“if”语句没有触发,我不知道为什么......测试urldomain.com/forum/index.php?topic=10126.msg36887
应该重定向到/success
,但它根本没有被重写。
这是我当前的 Nginx 配置:
location /forum/ {
index index.php index.html index.htm;
try_files $uri $uri/ /forum/index.php?$uri&$args;
location /forum/index.php {
# I know Nginx 'If is Evil', but it's the only way
# to trigger rewrites on url parameters
if ($arg_topic ~ [0-9]+\.\bmsg([0-9]+) {
# testing whether 'if' triggers:
rewrite ^ /success? redirect;
# full rewrite:
# rewrite ^\/forum\/index\.php ^\/forum\/index\.php\?posts\/$1\/? redirect;
}
}
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
将它放在
server
配置块中应该可以工作:正则表达式应该正确匹配您需要的内容,并且通过将所需的 ID 存储在变量中,您可以稍后在重写中使用它。假设您在站点的其他部分没有“主题”参数,则实际上没有必要将其范围限定在某个位置 - 即使您这样做,您也可以更改重写的第一部分以匹配 /forum/index仅 .php。
如果它只是关于“主题”论点,这可能有效:
在 nginx.conf 的“http”级别声明以下“地图”:
在“服务器”级别添加适当的“位置”:
确保您在服务器级别指定了“root”指令,以便“SCRIPT_FILENAME”填充正确的值。
您也可以检查 '$topic_id' 是否为零(例如,topic_id= 缺失或值不正确)。
使用这个你的 '$_GET' 数组将包含如下内容: