摘要 Nginx作为一个服务器,具有众多转发规则。工作中用到使用Nginx配置一个端口下多个路径转发到html下不同目录。目前知道的有三种方法可以实现,分别是使用root+location、alias、try_files。 一、同一端口的路
Nginx作为一个服务器,具有众多转发规则。工作中用到使用Nginx配置一个端口下多个路径转发到html下不同目录。目前知道的有三种方法可以实现,分别是使用root+location、alias、try_files。
假设一个场景,目前/var/www/目录下放了两个项目,目录名分别为masrt,backup,现在需要通过访问localhost/test访问test项目,通过访问localhost/demo访问demo项目。
使用root+location方法实现,只需要将要访问的目录作为location,root设置为项目所在的目录即可,当前场景下,即为配置一个location为/test/,然后将root设置为html,在配置一个location为/api/,然后root设置为html,root配置文件路径的效果即为将请求转发到root路径/location/对应的路径下,root配置时,路径可以以/结尾,也可以不写,都不影响。具体配置如下:
#虚拟主机的配置server {#监听端口listen 80;#域名,可以有多个,用空格隔开server_name localhost;#配置根目录以及默认页面location /test/ {root /var/www/master;index index.html index.htm;}#配置根目录以及默认页面location /api/ {root /var/www/html;index index.html index.htm;}#出错页面配置error_page 500 502 503 504 /50x.html;#/50x.html文件所在位置location = /50x.html {root html;} }
alias的作用,其实就是将配置的alias对应的路径替换location中指定的路径,当前场景下,即为配置一个location为/test/,然后将alias设置为html/test/,在配置一个location为/demo/,然后alias设置为html/demo/,需要特别注意是,alias后面必须要用“/”结束,否则会找不到文件,具体配置如下:
#虚拟主机的配置server {#监听端口listen 80;#域名,可以有多个,用空格隔开server_name localhost;#配置根目录以及默认页面location / {root /var/www/master;index index.html index.htm;}#配置根目录以及默认页面location /api/ {alias /var/www/html;index index.html index.htm;}#出错页面配置error_page 500 502 503 504 /50x.html;#/50x.html文件所在位置location = /50x.html {root html;} }
try_files的作用类似于转发,作用是尝试在硬盘中查找文件对应到与location中配置匹配的路径。在当前常见下,配置一个location为/api/,然后root配置为html/,然后配置try_files $uri $uri/ /api/index.html;$uri表示的是请求地址,如果请求路径为localhost/test/a.html,nginx会依次查找:
server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location ^~ /demo/ { root html/; try_files $uri $uri/ /demo/index.htm; }location ^~ /test/ { root html/; try_files $uri $uri/ /test/index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
#虚拟主机的配置server {#监听端口listen 80;#域名,可以有多个,用空格隔开server_name localhost;#配置根目录以及默认页面location / {root /var/www/master;index index.html index.htm;}#出错页面配置error_page 500 502 503 504 /50x.html;#/50x.html文件所在位置location = /50x.html {root html;} }#虚拟主机的配置server {#监听端口listen 88;#域名,可以有多个,用空格隔开server_name localhost;#配置根目录以及默认页面location / {root /var/www/backup/;index index.html index.htm;}#出错页面配置error_page 500 502 503 504 /50x.html;#/50x.html文件所在位置location = /50x.html {root html;} }
来源地址:https://blog.csdn.net/weixin_41605937/article/details/129715822
--结束END--
本文标题: Nginx——SeverName配置规则
本文链接: https://www.lsjlt.com/news/390452.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-06-03
2024-06-03
2024-06-04
2024-06-03
2024-06-03
2024-06-03
2024-06-03
2024-06-04
2024-06-03
2024-06-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0