下载nginx:nginx: download
解压到英文目录
启动:切换到nginx解压目录,cmd启动nginx
start nginx
浏览器输入localhost:80(默认是监控80端口),看到欢迎界面。
更改nginx.conf文件
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8001;
server_name localhost;
location / {
#前端地址,访问localhost:8001,访问到前端项目
root D:\Projects\spring-boot-learn\imall-fore-end;
index index.html index.htm;
}
#后端端口,自定义匹配前缀 /api/ ,在Ajax发送请求时,就可以发送到后端
location /api/ {
proxy_pass http://localhost:8000/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
nginx中location匹配规则
1.前缀匹配:不带符号
server {
listen 80;
server_name 192.168.100.123;
location /abc {
}
}
#可以匹配到
http://192.168.100.123/abc
http://192.168.100.123/abc?name=zs
http://192.168.100.123/abc/
http://192.168.100.123/abcd
# 下列写法,当输入http://192.168.100.123时匹配到
location / {
}
2.精确匹配:符号=
:表示精确匹配
server {
listen 80;
server_name 192.168.100.123;
location = /abc {
}
}
#可以匹配到
http://192.168.100.123/abc
http://192.168.100.123/abc?name=zs
#不能匹配到
http://192.168.100.123/abc/
http://192.168.100.123/abcd
3.正则匹配:符号~
与~*
:执行一个正则匹配,前者区分大小写,后者不区分
server {
listen 80;
server_name 192.168.100.123;
location = ~* \.(jpg|png|gif)$ {
}
}
4.符号^~
:一旦匹配到,就不继续匹配
server {
listen 80;
server_name 192.168.100.123;
# 匹配静态文件
location ^~ /static/ {
}
}
5.匹配优先级
- 1.精确匹配 =:如果匹配到,匹配结束,否则往下匹配;
- 2.前缀匹配(三种情况):
- (1)如果匹配到,记录所有成功项,最长项如果有^~,停止匹配;
- (2)如果匹配到,记录所有成功项,最长想如果没有^~,进行正则匹配;
- (3)如果没有匹配到,进行正则匹配
- 3.正则匹配 ~与~*:从上往下匹配,以最后一个匹配项为匹配结果
- 4.没有匹配项,返回404
proxy_pass规则
(nginx中location匹配规则与proxy_pass代理转发_skybulex的博客-CSDN博客_nginx的location转发规则)
api访问地址:http://192.168.1.123/user/test_user为例,server_name
为192.168.1.123,其中末尾是否带/
有比较多的情况,在使用时需要特别注意
情况1:location带/且proxy_pass带/
location /imall-api/ {
proxy_pass http://localhost:8000/;
}
#代理地址 http://192.168.1.123:8000/user/user_test
#前端ajax:
const baseUrl = "/imall-api";
function test() {
$.ajax({
url: baseUrl+"/user/user_test",
type: "get",
data: {},
async: true,
dataType: "json",
success: function (data) {
console.log(data);
},
})
}