匹配规则
location [=|~|~*|^~|@] /uri/ {
...
}
- = : 表示精确匹配后面的url
- ~ : 表示正则匹配,但是区分大小写
- ~* : 正则匹配,不区分大小写
- ^~ : 表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
- @ : “@” 定义一个命名的 location,使用在内部定向时,例如 error_page
结构
Global: nginx 运行相关
Events: 与用户的网络连接相关
http
http Global: 代理,缓存,日志,以及第三方模块的配置
server
server Global: 虚拟主机相关
location: 地址定向,数据缓存,应答控制,以及第三方模块的配置
root
location /i/ {
root /data/w3;
}
对于请求 pathname 为 /i/top.gif, /data/w3/i/top.gif 将被返回
文件的路径是 通过向 root 指令的值追加 pathname 来构造的
alias
Defines a replacement for the specified location.
location /i/ {
root /data/w3;
}
on request of /i/top.gif
, the file /data/w3/images/top.gif
will be sent.
When location matches the last part of the directive’s value:
location /images/ {
alias /data/w3/images/;
}
it is better to use the root directive instead:
location /images/ {
root /data/w3;
}
try_files
排序 检查存在 文件处理 ifnx=>内部重定向
Syntax: try_files file … uri;
try_files file … =code;
Default: —
Context: server, location
Description: Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made.
server {
listen 8888; # 自定义
server_name localhost;
root /xxx/dist; # vue 项目的打包后的dist
location / {
try_files $uri $uri/ @router; # 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
# 对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
# 因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last; /index.html前面有空格
}
# .......略
}
例子
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
// global设置,nginx运行相关
events{
// 与用户的网络连接相关
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$http_host" "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream jenkins{
server 127.0.0.1:8081;
}
server {
listen 80;
location ~* ^/document$ {
return 702;
}
}