我发现nginx的$request_uri重复了查询参数。
我想实现的目标是将裸域的任何请求重定向到www域。下面是一个示例配置。
server {
listen 8080;
server_name localhost;
location / {
if ($http_host !~* "^www\.") {
rewrite (.*) http://www.$http_host$request_uri permanent;
}
}
}
我得到的结果是:
curl -I http://127.0.0.1:8080/pp/\?a\=b
HTTP/1.1 301 Moved Permanently
Server: nginx/1.6.2
Date: Thu, 22 Jan 2015 04:07:39 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://www.127.0.0.1:8080/pp/?a=b?a=b
查询参数在结果中重复;我是不是遗漏了什么?
发布于 2015-02-19 02:19:24
您看到的查询参数的复制是Nginx的预期行为。要更改这一点,您需要在重写中添加一个尾随?
,如下所示:
server {
listen 8080;
server_name localhost;
location / {
if ($http_host !~* "^www\.") {
rewrite (.*) http://www.$http_host$request_uri? permanent;
}
}
}
如果替换字符串包含新的请求参数,则以前的请求参数将附加在这些参数之后。如果这是不需要的,则在替换字符串的末尾添加问号可避免附加这些字符串,例如:
重写^/users/(.*)$ /show?user=$1?最后;
然而,Aleksey Deryagin给出的配置对于您想要的重定向类型是更好、更有效的选项,因为在您的原始配置中,无论是否需要,每个请求都将由if
块进行评估。
发布于 2015-02-18 19:18:29
if is evil (并不总是如此,但是)所以为什么不尝试返回301:
server {
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
server {
server_name www.example.com;
root /var/www;
location / {
index index.html;
}
}
https://stackoverflow.com/questions/28081159
复制