社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  NGINX

职业:《深入理解nginx》nginx路由配置

王江涛_6000 • 5 年前 • 136 次点击  

下面介绍一下文件路径的定义配置项。

(1)以root方式设置资源路径

语法:root path;

默认:root html;

配置块:http、server、location、if

例如,定义资源文件相对于HTTP请求的根目录。

location /download/ {  root /opt/web/html/;}

在上面的配置中,如果有一个请求的URI是/download/index/test.html,那么Web服务器将会返回服务器上/opt/web/html/download/index/test.html文件的内容。

(2)以alias方式设置资源路径

语法:alias path;

配置块:location

alias也是用来设置文件资源路径的,它与root的不同点主要在于如何解读紧跟location后面的uri参数,这将会致使alias与root以不同的方式将用户请求映射到真正的磁盘文件上。例如,如果有一个请求的URI是/conf/nginx.conf,而用户实际想访问的文件在/usr/ local/nginx/conf/nginx.conf,那么想要使用alias来进行设置的话,可以采用如下方式:

location /conf {            alias /usr/local/nginx/conf/;}

如果用root设置,那么语句如下所示:

location /conf {            root /usr/local/nginx/;}

使用alias时,在URI向实际文件路径的映射过程中,已经把location后配置的/conf这部分字符串丢弃掉,因此,/conf/nginx.conf请求将根据alias path映射为path/nginx.conf。root则不然,它会根据完整的URI请求来映射,因此,/conf/nginx.conf请求会根据root path映射为path/conf/nginx.conf。这也是root可以放置到http、server、location或if块中,而alias只能放置到location块中的原因。

alias后面还可以添加正则表达式,例如:

location ~ ^/test/(\w+)\.(\w+)$ {    alias /usr/local/nginx/$2/$1.$2;}

这样,请求在访问/test/nginx.conf时,Nginx会返回/usr/local/nginx/conf/nginx.conf文件中的内容。

(3)访问首页

语法:index file ...;

默认:index index.html;

配置块:http、server、location

有时,访问站点时的URI是/,这时一般是返回网站的首页,而这与root和alias都不同。这里用ngx_http_index_module模块提供的index配置实现。index后可以跟多个文件参数,Nginx将会按照顺序来访问这些文件,例如:

location / {    root  path;    index /index.html /html/index.php /index.php;}

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37803
 
136 次点击