如何正确地为查询类型设置位置和重写:
请求:
site.com/a/?f=qwerty
重写为:
/a/?f=qwerty
请求:
site.com/b/?g=qwerty
重写为:
/b/?g=qwerty
请求:
site.com/anyshorttext/?h=qwerty
重写为:
/special/?h=qwerty
我应用了这些解决方案:
server {
location ~ /a/?(.*)$ {
rewrite ^/([-\w]+) /a/?m=$1 break;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
}
}
location ~ /b/?(.*)$ {
rewrite ^/([-\w]+) /b/?m=$1 break;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
}
}
location ~* ^/[a-zA-Z0-9/_$/]+$ {
rewrite ^/([-\w]+) /special/?h=$1 break;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
}
}
}
但在这种情况下,请求只会转发到 / special /
谢谢。
答案 0 :(得分:0)
您的示例意味着查询字符串不会针对每种情况进行更改。如果是这样,您可以尝试以下方法:
map $uri $special_query {
# $special_query will be true, for paths like: //site.com/xyz/?stuff
~^/[^/]+/$ $query_string;
}
server {
location / {
if ($special_query) {
return 301 "/special/?$query_string";
}
}
# these locations will override the default / location
location = /a/ {}
location = /b/ {}
location = /special/ {}
}
此解决方案既不使用正则表达式位置也不使用重写,这两种方法都会给配置增加不必要的复杂性并破坏自然的nginx流。 (参见nginx作者Igor Sysoev的可扩展配置:_thread
)