Appearance
动静分离
静态请求直接从 nginx 中请求拿到,而不是由 nginx 去应用服务器中请求,动态请求才 nginx 去应用服务器中请求。
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.rainx.top;
location / {
# 代理到应用服务器
proxy_pass http://192.168.44.102;
}
# 应用服务器的静态文件上传到 nginx/html 下
location /js {
root html;
index index.html index.htm;
}
location /css {
root html;
index index.html index.htm;
}
location /img {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}通过正则优化配置
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.rainx.top;
location / {
proxy_pass http://192.168.44.102;
}
location ~*/(js|css|img) {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}location 前缀
/ 通用匹配,任何请求都会匹配到。
= 精准匹配,不是以指定模式开头
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
^~ 非正则匹配,匹配以指定模式开头的location
location 的匹配顺序
多个正则 location 直接按书写顺序匹配,成功后就不会继续往后面匹配普通(非正则)location 会一直往下,直到找到匹配度最高的(最大前缀匹配)。当普通 location 与正则 location 同 时存在,如果正则匹配成功,则不会再执行普通匹配。所有类型 location 存在时, = 匹配 > ^~ 匹配 > 正则匹配 > 普通(最大前缀匹配)。
alias vs root
nginx
location /css {
alias /usr/local/nginx/static/css;
index index.html index.htm;
}root 用来设置根目录,而 alias 在接受请求的时候在路径上不会加上 location。
alias 指定的目录是准确的,即 location 匹配访问的 path 目录下的文件直接是在 alias 目录下查找的;
root 指定的目录是 location 匹配访问的 path 目录的上一级目录,这个 path 目录一定要是 真实存在 root 指定目录下的;
使用 alias 标签的目录块中不能使用 rewrite 的 break(具体原因不明);另外,alias 指定的目录后面必须要加上 /
alias 虚拟目录配置中,location 匹配的 path 目录如果后面不带 /,那么访问的 url 地址 中这个 path 目录后面加不加 / 不影响访问,访问时它会自动加上 /; 但是如果 location 匹配的 path 目录后面加上 /,那么访问的 url 地址中这个 path 目录必须要加上 /,访问时 它不会自动加上 / 。
root 目录配置中,location 匹配的 path 目录后面带不带 /,都不会影响访问。