nginx 学习之root 与 alias、正则、proxy_pass

1,431 阅读1分钟

root 与 alias

root

配置:

  location /testroot {
            root D:/nginx-1.16.1/html/3dTransform/;
            index  index.html index.htm;
		 	try_files $uri $uri/ /index.html;
        }

使用 root 指定路径时,访问 url + /testroot。具体路径将会指向 D:/nginx-1.16.1/html/3dTransform/testroot 下的文件。而当 testroot 文件夹不存在时,页面将访问不到,而将会跳转到nginx的index.html 。

alias

配置:

location /testroot {
            alias D:/nginx-1.16.1/html/3dTransform/;
            index  index.html index.htm;
		 	try_files $uri $uri/ /index.html;
        }

alias 与 root 不同,具体路径将会指向 D:/nginx-1.16.1/html/3dTransform 下的文件。

root 与 alias总结

配置:

location /uri {
            alias(root)  path;
       }

root: path + /uri 目录的文件 alias: path 目录的文件

nginx正则

语法规则

Nginx配置中Location的语法规则

location [ = | ~ | ~* | ^~ | !~ | !~* ] /uri/
{ }
  1. = 表示精确匹配
  2. ~ 表示区分大小写正则匹配
  3. ~* 表示不区分大小写正则匹配
  4. ^~ 表示URI以某个常规字符串开头
  5. !~ 表示区分大小写正则不匹配
  6. !~* 表示不区分大小写正则不匹配
  7. / 通用匹配,任何请求都会匹配到
root 使用正则
location ^~ /static/ {
			  root E:\assets;
			}

访问:http://192.168.16.12:8040/static/login_bg.jpg = E:/assets/static/login_bg.jpg 由 以上可知,root的路径,需要在 E:\assets 目录创建一个 static的文件夹

alias使用正则
location ^~ /static/ {
			  alias E:/assets/;
			}

访问:http://192.168.16.12:8040/static/login_bg.jpg = E:/assets/login_bg.jpg 注:在末尾 加上 ‘/’。 alias 使用 ,* 之类的正则。

location  ~ /alert-model/ {
            alias D:/nginx-1.16.1/html/3dTransform/;
            index  index.html index.htm;
		 	try_files $uri $uri/ /index.html;
		
		}

访问:http://192.168.16.12:8040//alert-model/ = D:/nginx-1.16.1/html/3dTransform/alert-model; 这时 需要在3dTransform 目录下创建 alert-model文件夹。

proxy_pass

配置:

location  ^~ /alert-model/ {

			proxy_set_header HOST $host;
			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://127.0.0.1:8041/;
		}

访问: http://192.168.16.12:8040/alert-model/ = http://192.168.16.12:8041/