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

发布时间 2023-10-10 12:58:24作者: 技术颜良

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

多多小老虎

于 2020-10-22 10:47:57 发布

2985
收藏 3
分类专栏: devops
版权

devops
专栏收录该内容
36 篇文章1 订阅
订阅专栏
文章目录
前言
一、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 则对 ”/” 可有可无。(之前就踩过这个坑)
————————————————
版权声明:本文为CSDN博主「多多小老虎」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_36759535/article/details/109217136