nginx重定向功能配置小结

由于工作原因,经常用到nginx,经过不断总结,在此汇总下nginx的url映射部分的特点和规律。

文件存储及调用url:

文件存放路径:D:\attached\attached\image\1571.jpg

调用的url为:http://localhost/attached/image/1571.jpg

一:rewrite写法

rewrite需要root配合,两种方式:

方式1:

location /attached/ {
            root   /;
            rewrite ^/image/(.*)$ d://attached/$1 break; 
            autoindex on; #启用目录索引功能
            autoindex_exact_size off; 
            autoindex_localtime on;        
        }

如上所示,这里的root为:/,即:盘符位置,假如我的nginx安装在D盘,那么这里就是指向D盘。

方式2:

location /attached/ {
            root D:/attached/;
            #使用 nginx rewrite 指令
            rewrite ^/image/(.*?)$ /$1 break;
        }

二:alias写法

指定root时:

 location / {
            root   D:\attached\attached;
            index  index.html index.htm;
        }
location ^/image/ {
            alias  \image;
            autoindex on;
    }

访问http://localhost/attached/image/1571.jpg即能成功。如果去掉^/iamge/映射,则出现404.

指定root,并且也指定image映射(访问路径:http://localhost/image/1571.jpg):

location / {
            root   D:/attached;
            index  index.html index.htm;
        }
location ^/image/ {
            alias  /image/;
            autoindex on;
    }

则需要在路径下有相应的文件:D:\attached\image\1571.jpg,url为:http://localhost/image/1571.jpg,也能访问成功。

不指定root,而直接用alias也可以:

location /attached/ {
            alias D:/attached/attached/;
            autoindex on;
            
        }

三:总结

root:nginx的配置文件中的root,如果没有指定,则指向nginx安装目录的html文件夹。

无论rewrite还是alias,模式均为root+重写(或者别名)部分,这样大概有2种技巧:1是root部分写多,重写部分写少;2是root部分写少,而重写部分写多。

以上如有错误,欢迎指出!

posted @ 2021-09-27 16:52  Shapley  阅读(1061)  评论(0编辑  收藏  举报