upstream apache {
server 127.0.0.1:8080;
}
server{
location ~* ^/service/(.*)$ {
proxy_pass http://apache/$1;
proxy_redirect off;
}
}
上面的代碼片段會將url包含字符串「service」的請求重定向到另一個服務器,但它不包括查詢參數。如何查詢字符串參數通過proxy_pass與nginx轉發?
upstream apache {
server 127.0.0.1:8080;
}
server{
location ~* ^/service/(.*)$ {
proxy_pass http://apache/$1;
proxy_redirect off;
}
}
上面的代碼片段會將url包含字符串「service」的請求重定向到另一個服務器,但它不包括查詢參數。如何查詢字符串參數通過proxy_pass與nginx轉發?
從proxy_pass文檔:
一種特殊的情況是在proxy_pass語句中使用的變量:不使用請求的URL,你是全權負責自己構建的目標URL。
由於您在目標中使用$ 1,因此nginx依賴於您準確告訴它要傳遞的內容。你可以用兩種方法解決這個問題。首先,剝離URI的開頭使用一個proxy_pass很簡單:
location /service/ {
# Note the trailing slash on the proxy_pass.
# It tells nginx to replace /service/ with/when passing the request.
proxy_pass http://apache/;
}
或者,如果你想使用正則表達式的位置,就包括ARGS:
location ~* ^/service/(.*) {
proxy_pass http://apache/$1$is_args$args;
}
我用略加修改的版本kolbyjack與~
而不是~*
的第二種方法。
location ~ ^/service/ {
proxy_pass http://apache/$uri$is_args$args;
}
我修改@kolbyjack代碼,使其工作於
http://website1/service
http://website1/service/
與參數
location ~ ^/service/?(.*) {
return 301 http://service_url/$1$is_args$args;
}
請記住,這將使服務器在重定向之前向客戶端返回301響應。上面的'proxy_pass'指令在服務器端進行重定向。 –
如果您的查詢參數包含URL(%)編碼字符,則會中斷。改用Andrew的答案。 –
你必須使用重寫通過使用PARAMS proxy_pass 我這裏是我做了angularjs應用部署到s3
S3 Static Website Hosting Route All Paths to Index.html
採納您的需求將是像
location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}
,如果你想結束在http://127.0.0.1:8080/query/params/
,如果你想結束在http://127.0.0.1:8080/service/query/params/ 你需要像
location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}
重定向不帶查詢字符串在監聽端口線下面的服務器塊中添加下面的行
if ($uri ~ .*.containingString$) { return 301 https://$host/$uri/; }
查詢字符串
if ($uri ~ .*.containingString$) { return 301 https://$host/$uri/?$query_string; }
nginx文檔是明確的,儘可能避免使用if。在這種情況下,解決方案可以正確使用'location',如其他答案中所示。 –
GitHub的要點https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7
#set $token "?"; # deprecated
set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`
if ($is_args) { # if the request has args update token to "&"
set $token "&";
}
location /test {
set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
# if no args $is_args is empty str,else it's "?"
# http is scheme
# service is upstream server
#proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
proxy_pass http://service$uri$is_args$args; # proxy pass
}
#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2
#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2
我不相信你能做到後者。我試過了,nginx向我抱怨。 – duma
抱怨怎麼樣?我只是在nginx 1.3.4上測試它,它對我來說工作得很好。 – kolbyjack
Humm ..現在我不記得了:(但是我覺得它可能與「〜*」有關,但是我只是查了一下,而且我有nginx 1.2。3(通過自制)。也許就是這樣? – duma