Nginx--location 与 rewrite 区块详解

本文详细介绍了Nginx中location区块的使用方法及其各种匹配规则,并演示了如何进行地址重写,包括精确匹配、默认匹配、路径匹配及扩展名匹配等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nginx location区块:
location 区块是通过用户访问的不同url来定义执行不同的应用。
location区块实在server区块下:
演示:
server {
listen 80 ;
server_name www.sina.com sina.com;
root html/www; << 网站根目录
location / { << / 用户请求的网站根目录index.html 文件
return 401; <<返回值为401
}
location = / { << 用户请求的完整url http://www.sina.com/ 。一般默认也是访问index
return 402;
}
location /documents/ { << 用户请求的 http://www.sina.com/documents/ ,返回值403
return 403;
}
location ^~ /images/ { << 优先匹配/images/路径
return 404 ;
}
location ~* \.(gif|jpg|jpge)$ { << 正则匹配
return 500;
}
access_log logs/fangwen.log main;
}
~

写完也可以用include导入虚拟主机文件。

用户请求的url详解:

当 location = / { 时, URL为空或者为/ = 的精确匹配优先级最高。 无论放置的位置如何,都是优先匹配的。
当 location / { 时 , / 为默认匹配,即没有匹配的其他location时,最后匹配默认 /
当 location /documents/ { 时,即路径匹配。如果后面有其他字符,会匹配结尾的字符。
当 Location ^~ /images/ { 注意前面的 ^~ 符号。即优先匹配路径。
当 location ~* \.(gif|jpg|jpeg)$ { 扩展名,如果出现字符会优先匹配扩展名


=============================================================================

Nginx rewrite 地址重写

nginx rewrite 地址重写,需要PCRE 软件库的支持。即正则表达。nginx rewrite一般编译的过程中会自动安装,只需安装pcre 软件即可。


server {
listen 80;
server_name blog.sina.com ;
location / {
root html/blog;
index index.html index.htm;
}
if ( $http_host ~* "^(.*) \.sina\.com$" ) {
set $domain $1;
rewrite ^(.*) http://www.sina.com/$domain/lishuo.html break ;
}
access_log logs/fangwen.log main;
}



=========================================================================
## rewrite module

server {
listen 80;
server_name www.a.sina.com ;
rewrite ^/(.*) http://www.sina1.com/$1 permanent; << rewrite 地址重写。
}

server {
listen 80;
server_name www.sina1.com ;
location / {
root html/blog;
index index.html index.htm;
}

access_log logs/fangwen.log main;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值