746 字
4 分钟
Nginx 安装、配置、代理设置
以下是关于 Nginx 安装、配置、代理设置以及代理管理的详细文档:
1. 检查 Nginx 是否已安装并运行
nginx -v
如果已安装,会显示 Nginx 的版本信息;如果未安装,可根据系统类型进行安装。
ps aux | grep nginx
如果 Nginx 正在运行,会显示主进程和工作进程信息。
2. 安装 Nginx
brew install nginx
安装完成后,Nginx 默认会监听在 http://localhost:8080。
# 对于基于 Debian 的系统(如 Ubuntu)sudo apt updatesudo apt install nginx
# 对于基于 Red Hat 的系统(如 CentOS)sudo yum install nginx
安装完成后,启动 Nginx 服务:
# 启动 Nginxsudo systemctl start nginx
# 设置开机自启sudo systemctl enable nginx
Nginx 默认会监听在 http://localhost:80。
3. 配置 Nginx
nginx -t
输出示例:
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is oknginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
这表示配置文件位于 /usr/local/etc/nginx/nginx.conf
。
nano /usr/local/etc/nginx/nginx.conf
在配置文件中,可以进行以下常见修改:
-
更改默认端口:
将
listen 8080;
改为listen 80;
,这样可以直接通过 http://localhost 访问。 -
更改默认根目录:
修改
root /usr/local/var/www;
为你想要的路径,例如:
root /Users/keke/Projects/website;
确保这个目录存在且有正确的权限。
server { listen 80; server_name localhost;
location / { proxy_pass http://127.0.0.1:3000; # 代理到本地的 3000 端口 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}
这将把对 http://localhost 的请求转发到本地的 3000 端口。
nginx -t
如果输出 syntax is ok
,表示配置正确。
# 重新加载配置sudo nginx -s reload
# 或者重启 Nginx 服务sudo systemctl restart nginx
如果使用 Homebrew 安装的 Nginx,可以使用以下命令:
brew services restart nginx
这将重新加载或重启 Nginx 服务以应用新的配置。
4. 配置代理设置
http { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;}
这将设置代理请求头,以便后端服务器可以获取客户端的真实 IP 和协议。
location / { proxy_pass http://127.0.0.1:3000; # 代理到本地的 3000 端口 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
这将把对 http://localhost 的请求转发到本地的 3000 端口。
Nginx 安装、配置、代理设置
https://fuwari.vercel.app/posts/util/nginx/