nginx通过alias别名使请求路径可以多变

it2025-09-11  6

文章目录

前言一、root二、alias三、样例总结


前言

UAT上有一个需求,只有一个公网域名,通过二级域名来区分不同环境,然而对于前端不同环境来说,只有前端只有一套代码,需要打包不同环境的包加不同目录,对于前端来说不友好,所以就通过nginx的配置来解决这个问题

这里主要用到root和alias 这两个指令都可以定义在location模块中,都是用来指定请求资源的真实路径

一、root

location /i/ { root /data/w; }

请求 http://foofish.net/i/top.gif 这个地址时,那么在服务器里面对应的真正的资源是 /data/w/i/top.gif文件

注意:真实的路径是root指定的值加上location指定的值 。

二、alias

而 alias 正如其名,alias指定的路径是location的别名,不管location的值怎么写,资源的 真实路径都是 alias 指定的路径 ,比如

location /i/ { alias /data/w/; }

同样请求 http://foofish.net/i/top.gif 时,在服务器查找的资源路径是: /data/w/top.gif

三、样例

前端打包的路径

通过alias的一份样例

控制台mgt

worker_processes 1; events { worker_connections 4000; } http { include /etc/nginx/mime.types; default_type application/octet-stream; client_max_body_size 50m; sendfile on; keepalive_timeout 65; server { listen 80 default_server; server_name localhost; location /iot/ { alias /usr/share/nginx/html/; index /index.html /index.htm; try_files $uri $uri/ /index.html; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }

组态interface

events { worker_connections 4000; } http { include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; root /usr/share/nginx/html; index index.html index.htm; location /iot/ { alias /usr/share/nginx/html/; try_files $uri $uri/ @router; index index.html index.htm; } location @router { rewrite ^.*$ /interface/index.html last; } } }

这样当强求http://interface.iot-tenant.192.74.158.32.nip.io/iot/interface/index.html 的时候实际就请求到 /usr/share/nginx/html/interface/index.html

总结

1、 alias 只能作用在location中,而root可以存在server、http和location中。

2、alias 后面必须要用 “/” 结束,否则会找不到文件,而 root 则对 ”/” 可有可无。(之前就踩过这个坑)

最新回复(0)