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;
}