本文共 2269 字,大约阅读时间需要 7 分钟。
下载Nginx
通过官方网站或第三方镜像站点下载适合Windows的Nginx安装包。注意选择与系统相兼容的版本。安装与配置
解压下载的Nginx安装包,找到nginx.exe或对应的安装脚本。在命令行执行安装命令:nginx.exe -w "D:\nginx" # 将路径替换为你的安装目录
或使用自动安装脚本:
nginx-install.bat
安装完成后,Nginx会自动生成配置文件。
设置环境变量
在命令行设置Nginx的环境变量:set NGINX_VERSION=1.23.1set PATH=%PATH%;%NGINX_VERSION%\modules\bin
确保路径正确。
访问权限设置
修改Nginx配置文件,确保允许所有IP访问:nginx -c "conf\nginx.conf" -s reload
或直接修改配置文件:
vi conf\nginx.conf
配置Nginx代理
根据需求编辑conf\nginx.conf文件,添加以下配置:events {}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 65; gzip on; server { listen 70; server_name 10.229.36.158; # 服务器IP地址 location / { root D:\www\kaoqin\dist\; # 前端静态资源目录 try_files $uri $uri/ /index.html; index index.html index.htm; } location /prod-api/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8080/; # 后端接口地址 } # 防止404错误 error_page 404 /50x.html; location /50x.html { root html; } }}启动Nginx
在Nginx安装目录打开命令行:start nginx.exe
或使用参数:
nginx.exe -s reload # 重新加载配置
访问测试
打开浏览器,访问服务器地址:http://10.229.36.158如果看到前端页面,说明静态资源加载成功。检查端口
确保Nginx监听的70端口开放。日志监控
查看Nginx访问日志:tail -f logs/access.log
请求未代理
确保location /和location /prod-api/的配置正确无误。跨域问题
在location /prod-api/中添加:proxy_set_header Access-Control-Allow-Origin *;proxy_set_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;proxy_set_header Access-Control-Allow-Headers X-Requested-With;
同时在前端应用中配置CORS。
后端接口访问问题
确保proxy_pass http://localhost:8080/的地址与后端服务一致。通过以上步骤,完成了前后端项目在Windows服务器上的部署及Nginx代理配置。Nginx作为高效的反向代理和负载均衡器,为前后端分离提供了可靠的解决方案。
转载地址:http://pecfk.baihongyu.com/