Windows安装并使用nginx配置跨域
一、安装nginx:
下载nginx,解压到“C:\”(Windows):
http://nginx.org/download/nginx-1.18.0.zip
二、nginx基本命令:
以管理员身份运行cmd
进入nginx根目录:
cd C:\nginx-1.18.0
启动nginx:
start nginx
重启nginx:
nginx -s reload
停止nginx:
nginx -s stop
测试配置文件格式是否正确:
nginx -t
关闭所有nginx进程:
taskkill /f /fi "imagename eq nginx.exe"
三、配置跨域:
1.使用vscode打开nginx配置文件:
code C:\nginx-1.18.0\conf\nginx.conf
2.修改配置文件:
#user nobody;
worker_processes 2; # 进程数
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024; # 最大连接数
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$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;
server {
listen 80; # 用户访问的地址是http://localhost,不带端口号就是80端口
server_name localhost;
location / {
proxy_pass http://localhost:8080; # 前端开发环境的域名
# try_files $uri $uri/ /index.html; # 前端线上环境,打包后放nginx根目录下html文件夹
}
location /api/ { # 这里设的是location /api/,根据需要灵活修改
proxy_pass http://localhost:3000; # 后端域名
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS'; # 根据需要灵活修改HTTP请求方法
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';
}
}
}
3.使用命令关闭nginx进程,再次启动nginx