![Apache - 如何将用户重定向到给定的 URL](https://linux22.com/image/673115/Apache%20-%20%E5%A6%82%E4%BD%95%E5%B0%86%E7%94%A8%E6%88%B7%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%E7%BB%99%E5%AE%9A%E7%9A%84%20URL.png)
在我的网站中,我有跨域请求,有时会出现 HTTP 302 响应。
我想做两件事:
- 对于 HTTP选项请求:HTTP 代码 200,无后续重定向
- 对于 HTTP发布,获取请求:跟随新的 URL 并根据需要执行所有 302。
由于 get 和 post 所遵循的 URL 多种多样(多个 API),我做了类似的事情:
http://myproxyurl.com?service=http://myapi.com(对 myapi.com URL 进行编码)
这是我的代理虚拟主机:
<VirtualHost *:80>
DocumentRoot "C:/..."
ServerName http://myproxyurl.com
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
RewriteCond %{QUERY_STRING} ^service=(.*)
RewriteRule (.*) $1 [R,L]
</VirtualHost>
但是有了它,我在 chrome 上就有了这样的重定向循环: Chrome 网络标签屏幕截图
我该如何修复这个重定向循环?如果有的话,我愿意接受比“?service=”更好的解决方案。
感谢帮助。
编辑:新的 Vhost 配置
和 :Mod-proxy 带有查询字符串替代吗?我快要找到解决方案了……但仍然收到代码 500
<VirtualHost *:80>
LogLevel alert rewrite:trace8
DocumentRoot "C:/..."
ServerName myproxyurl.com
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
AllowEncodedSlashes On
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
RewriteMap unescape int:unescape
RewriteCond %{QUERY_STRING} ^service=(.*)$
RewriteRule ^/ ${unescape:%1} [P,L]
</VirtualHost>
答案1
最终 VHOST:
<VirtualHost *:80>
DocumentRoot "C:/..."
ServerName myproxyurl.com
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
RewriteMap unescape int:unescape
RewriteCond %{QUERY_STRING} ^service=(.*)$
RewriteRule ^/ ${unescape:%1} [P,NE,R=302,L]
</VirtualHost>
不确定是否需要所有这些行/标志,但是我得到了结果!
您必须启用这些 Apache 模块:
- mod_rewrite
- 代理模块
- 代理http模块
- headers_module
很高兴知道:我读到这种方法不安全,因为任何人都可以将任何 URL 放置在服务参数中...就我而言,我可以信任用户。