如何从nginx发出相对URL重定向? [英] how to issue a relative url redirect from nginx?
问题描述
如何在nginx中配置重定向,以使用相对于特定路径的相对重定向来响应某个URL?
How can a redirect be configured in nginx to respond to a certain url with a relative redirect to a specific path?
nginx文档建议这是nginx的默认模式,但实际上,如果重定向到以/nginx开头的位置以位置"字段中的绝对URL进行响应.
The nginx documentation suggests that this is the default mode for nginx, but in reality if the location being redirected to starts with a / nginx is responding with an absolute url in the Location field.
对于包含位置的本地服务器配置:
For local server configuration containing locations:
location = /a {
return 301 some/path;
}
location = /b {
return 301 /qwerty;
}
对/a请求的响应位置为:
the response Location to a request to /a is:
Location: some/path
对于/b,它是:
Location: http://127.0.0.1/qwerty
但是,我们希望/b做出回应:
however, we would like /b to respond with:
Location: /qwerty
我们要使用相对重定向的原因是,我们希望从不同的域和代理访问nginx,例如可以通过dev或通过ssl终止负载均衡器来实现,并且宁可通过减轻需要了解该上下文的nginx来简化事情.
The reason we would like to use relative redirects is that we would like to access nginx from different domains and proxies, e.g. in clear in dev or via ssl-terminating load-balancer, and would rather keep things simple by relieving nginx of needing to understand that context.
仅供参考,这些示例使用例如curl进行了针对nginx版本1.4.6和1.9.6的测试:
FYI these examples were tested against nginx versions 1.4.6 and 1.9.6, using curl e.g.:
curl --head http://127.0.0.1/b
推荐答案
如果return
uri以/
开头,nginx标头过滤器总是插入<scheme>://<host>
.
(请参阅nginx源中的ngx_http_script_return_code()
和ngx_http_header_filter()
函数以供参考)
nginx header filter always inserts <scheme>://<host>
if return
uri starts with /
.
(see ngx_http_script_return_code()
and ngx_http_header_filter()
function in nginx source for reference)
因此,如果客户端(例如Google chrome)可以接受Location: /qwerty
,则可以使用以下配置:
So, if client (e.g. google chrome) can accept Location: /qwerty
, you can use the following configure:
location = /b {
return 301 " /qwerty"; # insert space char before "/qwerty"
}
另一种解决方案可以通过 lua-nginx-module 完全生成Location: /qwerty
add_header 指令:
Another solution can generate Location: /qwerty
exactly, via lua-nginx-module and add_header directive:
location = /b {
add_header Location "/qwerty";
content_by_lua 'ngx.exit(301)';
}
这个奇怪的配置如何工作?
How does this weird configure work?
- 使用
ngx.exit
以状态代码301退出,它不会创建"Location"标头(return
指令始终创建"Location"标头,即使标头值为空) - 使用
add_header
添加Location: /qwerty
标头,但不插入<scheme>://<host>
- use
ngx.exit
to exit with status code with 301, it does not create "Location" header (return
directive always create "Location" header, even empty header value) - use
add_header
to addLocation: /qwerty
header, it does not insert<scheme>://<host>
这篇关于如何从nginx发出相对URL重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!