一、环境
Windows系统、Nginx1.18.0
二、步骤
1、nginx解压根目录
D:\nginx-1.18.0
2、配置nginx.conf
文件路径:
D:\nginx-1.18.0\conf\nginx.conf
将nginx.conf内容修改为以下:
user root;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
client_max_body_size 2000m;
sendfile on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include conf.d/*.conf; #项目配置在conf.d文件夹下
}
3、不同项目设置不同的配置文件
在D:\nginx-1.18.0\conf
目录下创建文件夹conf.d
进入D:\nginx-1.18.0\conf\conf.d
目录创建demo.conf配置文件
#后端负载均衡(后端项目端口8911和8912)
upstream loadbalance {
server 127.0.0.1:8911 max_fails=3 fail_timeout=30s weight=2;
server 127.0.0.1:8912 max_fails=3 fail_timeout=30s weight=2;
}
server {
#前端项目访问端口8098
listen 8098;
server_name localhost;
charset utf-8;
location /api {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
# 前端调用接口时有/api的url都会转发到后端(loadbalance为上面upstream关键字后面的名字)
proxy_pass http://loadbalance;
}
location / {
# 前端项目地址,D:\nginx-1.18.0根目录下的demo文件夹
root demo;
index index.html index.htm;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^.*$ /index.html last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}