我希望 nginx 处理:
http://dev.mydomain.com/about-us作为
http://dev.mydomain.com/index.cfm/about-us
在加载 index.cfm 文件时,Nginx 还必须传递“cgi 路径信息”(/about-us)以供服务器处理。我非常接近了,但看到了一些意想不到的结果。
这是我当前的 nginx 配置:
server {
listen 80 default_server;
server_name _;
index index.cfm index.html index.htm;
root /var/www;
server_name_in_redirect off;
set $path_info $request_uri;
try_files $uri /index.cfm$args;
location ~* \.(cfm|cfc|cfr)$ {
proxy_pass http://127.0.0.1:8888;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header XAJP-PATH-INFO $path_info;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
如果 URL 中未提供 index.cfm(例如上面的“about-us”示例),则此路由将正确路由到 index.cfm。但是,我觉得奇怪的是,显式请求 index.cfm,例如http://dev.mydomain.com/index.cfm实际上提示用户下载文件(就像服务器不知道如何处理它一样)。
答案1
您的做法是正确的try_files
。但是您想附加完整的 URL 路径,而不是像以前那样附加查询字符串。例如:
try_files $uri /index.cfm$uri;
答案2
如果我理解正确的话,你可以尝试以下设置
server {
listen 8989;
server_name localhost;
index index.html;
location / {
return 301 $scheme://$http_host/index.cfm$uri;
}
location ~ /index.cfm {
root /vhosts/default;
}
}
一些基本检查
# curl -I http://localhost:8989/
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:40:29 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://localhost:8989/index.cfm/
# curl -I http://localhost:8989/index.cfm/
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:40:37 GMT
Content-Type: text/html
Content-Length: 65
Last-Modified: Fri, 19 Feb 2016 23:27:42 GMT
Connection: keep-alive
ETag: "56c7a4ee-41"
Accept-Ranges: bytes
# curl -I http://localhost:8989/test.html
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:40:55 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://localhost:8989/index.cfm/test.html
# curl -I http://localhost:8989/index.cfm/test.html
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:41:05 GMT
Content-Type: text/html
Content-Length: 64
Last-Modified: Fri, 19 Feb 2016 23:27:36 GMT
Connection: keep-alive
ETag: "56c7a4e8-40"
Accept-Ranges: bytes
# curl -I http://localhost:8989/non_exist_file.html
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:42:56 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://localhost:8989/index.cfm/non_exist_file.html
# curl -I http://localhost:8989/index.cfm/non_exist_file.html
HTTP/1.1 404 Not Found
Server: nginx/1.8.0
Date: Sat, 20 Feb 2016 01:43:05 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive
不过,我宁愿不做任何实际的重定向,只是“重写”。
我建议阅读以下主题
- https://www.nginx.com/blog/creating-nginx-rewrite-rules/
- https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites
大多数情况下,回报是更可取的。