NGINX重写配置需求:将/files路径重定向到根域名
NGINX反向重写URL配置问题
当前可正常访问https://files.mydomain.com/files,但访问https://files.mydomain.com时会自动重定向到https://files.mydomain.com/files。需要实现反向逻辑:将https://files.mydomain.com/files重定向到https://files.mydomain.com,同时保证根路径能正确代理到后端服务。
当前NGINX配置
http { server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 80; server_name files.mydomain.com; location / { return 301 https://files.mydomain.com$request_uri; } } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name files.mydomain.com; client_max_body_size 0; location / { return 301 https://$host/files; } location /files { proxy_pass http://localhost:89; } } #Root Domain server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name_in_redirect off; server_name www.mydomain.com mydomain.com; log_not_found off; location / { root /inetpub/wwwroot; index index.html index.htm; } } }
尝试的配置及问题
修改后访问https://files.mydomain.com会跳转到NGINX默认欢迎页,配置如下:
http { server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 80; server_name files.mydomain.com; location / { return 301 https://files.mydomain.com$request_uri; } } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name files.mydomain.com; client_max_body_size 0; location ^~ /files { rewrite ^/files/?(.*)$ https://files.mydomain.com/$1 permanent; proxy_pass http://localhost:89/files; } } #Root Domain server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name_in_redirect off; server_name www.mydomain.com mydomain.com; log_not_found off; location / { root /inetpub/wwwroot; index index.html index.htm; } } }
正确配置方案
问题出在尝试的配置中删除了根路径location /,导致访问https://files.mydomain.com时匹配不到自定义规则,触发NGINX默认的server块。以下是修正后的配置:
http { server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 80; server_name files.mydomain.com; location / { return 301 https://files.mydomain.com$request_uri; } } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name files.mydomain.com; client_max_body_size 0; # 处理/files开头的请求,重定向到根路径对应位置 location ~ ^/files(/.*)?$ { return 301 https://$host$1; } # 根路径直接代理到后端的/files路径 location / { proxy_pass http://localhost:89/files; } } #Root Domain server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name_in_redirect off; server_name www.mydomain.com mydomain.com; log_not_found off; location / { root /inetpub/wwwroot; index index.html index.htm; } } }
关键说明
location ~ ^/files(/.*)?$:正则匹配所有以/files开头的路径,将其重定向到根路径,保留后续的路径部分(比如/files/doc会重定向到/doc)location /:根路径直接代理到后端服务的/files路径,这样访问https://files.mydomain.com时会直接获取后端/files下的内容,无需重定向- 保留了原有HTTP到HTTPS的重定向规则,确保所有请求都走HTTPS
内容的提问来源于stack exchange,提问作者MKANET
相关产品推荐
相关产品推荐

