返回
NGINX 配置及跨域配置之 Windows 下部署指南
前端
2023-11-18 01:37:37
NGINX 简介
NGINX 是一款高性能的 HTTP 和反向代理服务器,因其轻量级、高稳定性和丰富的功能而受到广大用户的喜爱。它可以作为独立的 Web 服务器,也可作为负载均衡器或反向代理服务器,并可以通过丰富的模块进行功能扩展。
Windows 下部署 Nginx
1. 下载并安装 Nginx
首先,从 Nginx 官网下载适合您系统版本的安装包,并将其安装在您选择的目录下。安装过程中,请确保您已选中“开机启动”和“自动启动”选项,以保证 Nginx 在系统启动时自动运行。
2. 配置 Nginx
- 打开 Nginx 的配置文件 nginx.conf,通常位于安装目录下的 conf 文件夹中。
- 在配置文件中,找到 http {} 块,并在其中添加以下配置:
# 日志配置
error_log logs/error.log info;
access_log logs/access.log main;
# 工作进程配置
worker_processes 2;
events {
worker_connections 1024;
}
# HTTP 模块配置
http {
include mime.types;
default_type application/octet-stream;
# 启用代理功能
proxy_temp_path c:/nginx/temp;
proxy_cache_path c:/nginx/cache levels=1:2 keys_zone=my_cache:10m;
proxy_ignore_headers "X-Forwarded-For";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
# 跨域配置
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
add_header Access-Control-Allow-Headers Content-Type, Authorization;
}
3. 启动 Nginx
在 cmd 中切换到 Nginx 的安装目录,并执行以下命令启动 Nginx:
nginx.exe -s start
4. 测试 Nginx
使用浏览器访问 http://localhost,如果页面正常显示,则表示 Nginx 已成功安装并配置。
跨域配置
跨域资源共享 (CORS) 是一种机制,它允许 Web 应用程序向其他域的服务器发送跨域请求。Nginx 可以通过在配置文件中添加以下配置来启用 CORS:
# 跨域配置
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
add_header Access-Control-Allow-Headers Content-Type, Authorization;
总结
通过本指南,您已成功在 Windows 系统中安装并配置了 Nginx,并解决了跨域问题。Nginx 是一款功能强大的 Web 服务器,它可以满足您各种 Web 应用的需求。希望本指南对您有所帮助。