分享一下 nginx 配置一个简单的 web 网站

xml 复制代码
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
#server {
#	listen 80;
#	listen [::]:80 default_server;

	# SSL configuration
	#
	# listen 443 ssl default_server;
	# listen [::]:443 ssl default_server;
	#
	# Note: You should disable gzip for SSL traffic.
	# See: https://bugs.debian.org/773332
	#
	# Read up on ssl_ciphers to ensure a secure configuration.
	# See: https://bugs.debian.org/765782
	#
	# Self signed certs generated by the ssl-cert package
	# Don't use them in a production server!
	#
	# include snippets/snakeoil.conf;

	#root /var/www/html;
        #root /home/ubuntu/dist;
        #index index.html
	# Add index.php to the list if you are using PHP
	#index index.html index.htm index.nginx-debian.html;

#	server_name _;

#	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
                #proxy_pass http://7.223.97.50:8081;
#		try_files $uri $uri/ =404;
#	}

	# pass PHP scripts to FastCGI server
	#
	#location ~ \.php$ {
	#	include snippets/fastcgi-php.conf;
	#
	#	# With php-fpm (or other unix sockets):
	#	fastcgi_pass unix:/run/php/php7.4-fpm.sock;
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	#}

	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	#location ~ /\.ht {
	#	deny all;
	#}
#}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#

server {
	listen 80;
#	listen [::]:80;

	server_name _;

	#root /home/ubuntu/dist/;
	#index index.html;

	location / {
		root /home/ubuntu/MHS/dist/;
                index index.html index.htm;
		try_files $uri $uri/ @router;
                #proxy_pass http://localhost:8080;
	}

        location /api/   {
                #rewrite ^/api/(.*)$ /$1 break;
                proxy_pass http://localhost:8080;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location @router {
                 rewrite ^.*$ /index.html last;
        }
	
}

server {
	listen 81;
#	listen [::]:80;

	server_name _;

	#root /home/ubuntu/dist/;
	#index index.html;

	location / {
		root /home/ubuntu/dist/;
                index index.html index.htm;
		try_files $uri $uri/ index.html;
                #proxy_pass http://localhost:8081;
	}

        location /prod-api/   {
                rewrite ^/prod-api/(.*)$ /$1 break;
                proxy_pass http://localhost:8081/;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

分享一下 nginx 配置一个简单的 web 网站

在部署前端项目或静态网站时,Nginx 是最常用、最稳定的 Web 服务器之一。很多新手面对 Nginx 配置文件时会感到头大,其实只要掌握核心逻辑,配置一个简单的 Web 服务并不复杂。

今天我将结合一段真实的 Nginx 配置代码,带你拆解如何配置一个支持静态资源托管 、SPA 路由重写 以及后端 API 代理的完整 Web 站点。


1. 配置文件概览

这段配置展示了两个虚拟主机(Server Block):

  1. 端口 80:用于主站,支持 Vue/React/Next.js 等前端框架的历史路由刷新问题(SPA Routing)。
  2. 端口 81:用于另一个独立站点,配置了带有前缀的 API 代理。

核心配置代码

nginx 复制代码
# 主站点配置 (端口 80)
server {
    listen 80;
    server_name _; # 默认捕获所有域名请求

    root /home/ubuntu/MHS/dist/; # 静态文件根目录
    index index.html index.htm;

    # 核心逻辑:处理前端路由
    location / {
        try_files $uri $uri/ @router;
    }

    # 处理 API 请求代理
    location /api/ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 路由重写规则 (解决 SPA 刷新 404 问题)
    location @router {
        rewrite ^.*$ /index.html last;
    }
}

# 独立站点配置 (端口 81)
server {
    listen 81;
    server_name _;

    root /home/ubuntu/dist/;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ index.html;
    }

    # 带前缀的 API 代理,并去除前缀
    location /prod-api/ {
        rewrite ^/prod-api/(.*)$ /$1 break;
        proxy_pass http://localhost:8081/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

2. 逐段深度解析

2.1 基础结构:server 块

nginx 复制代码
server {
    listen 80;
    server_name _;
    ...
}
  • listen 80:监听标准的 HTTP 端口。
  • server_name _:这是一个通配符写法。在实际生产环境中,建议替换为你的域名(如 www.example.com)。使用 _ 表示如果没有其他匹配的域名,就使用这个配置作为默认站点。

2.2 静态资源托管:root 与 index

nginx 复制代码
root /home/ubuntu/MHS/dist/;
index index.html index.htm;
  • root:指定了服务器查找文件的物理路径。当用户访问 http://your-ip/ 时,Nginx 会去 /home/ubuntu/MHS/dist/ 目录下寻找 index.html。
  • index:定义默认读取的文件顺序。

2.3 解决 SPA 刷新 404 问题(重点!)

这是现代前端框架(Vue, React, Angular)部署最容易踩坑的地方。

nginx 复制代码
location / {
    try_files $uri $uri/ @router;
}

location @router {
    rewrite ^.*$ /index.html last;
}

原理解析:

  1. 当用户访问 http://your-ip/user/123 时,Nginx 首先检查 /home/ubuntu/MHS/dist/user/123 是否是一个存在的文件或目录。
  2. 因为这是一个单页应用(SPA),服务器上并没有 user/123 这个文件夹,所以 $uri 和 $uri/ 都会失败。
  3. 此时执行 @router 标签。
  4. rewrite ^.*$ /index.html last; 将请求重写为 /index.html。
  5. Nginx 返回 index.html,前端 JS 接管路由,从而正确显示页面内容。

如果没有这段配置 :用户直接访问子路由链接,或者刷新页面,浏览器会向服务器请求 /user/123,服务器找不到文件,返回 404 Not Found。

2.4 API 反向代理

nginx 复制代码
location /api/ {
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

原理解析:

  • 当用户请求 /api/getUser 时,Nginx 将其转发给本地的后端服务 http://localhost:8080/getUser。

  • 注意路径处理 :这里 proxy_pass 后面没有 加斜杠 /。

    • 如果写成 proxy_pass http://localhost:8080/,那么请求 /api/getUser 会被转发为 /getUser(去掉 /api)。
    • 如果写成 proxy_pass http://localhost:8080,那么请求 /api/getUser 会被转发为 /api/getUser(保留原路径)。
    • 注:根据你提供的配置,它是保留路径的,请确保你的后端接口确实以 /api 开头。
  • Header 设置:

    • Host:告诉后端服务原始请求的域名。
    • X-Real-IP / X-Forwarded-For:将用户的真实 IP 传递给后端,否则后端只能看到 127.0.0.1。

2.5 带前缀的代理与重写(端口 81 配置)

nginx 复制代码
location /prod-api/ {
    rewrite ^/prod-api/(.*)$ /$1 break;
    proxy_pass http://localhost:8081/;
    ...
}

原理解析:

  • 这个配置常用于多环境部署或微服务架构。
  • rewrite ^/prod-api/(.*)$ /$1 break;:
    • 将 URL /prod-api/users/login 中的 /prod-api/ 去掉,变成 /users/login。
    • break 表示立即停止后续 rewrite 规则,并立即执行 proxy_pass。
  • proxy_pass http://localhost:8081/;:
    • 注意末尾的斜杠 /。结合上面的 rewrite,最终请求发往后端的是 http://localhost:8081/users/login。

3. 部署步骤指南

  1. 保存配置 :

    将上述内容保存为 /etc/nginx/sites-available/your-site.conf。

  2. 创建软链接(启用配置):

    bash 复制代码
    sudo ln -s /etc/nginx/sites-available/your-site.conf /etc/nginx/sites-enabled/

    注:确保删除了默认的 default 软链接,否则可能会冲突。

  3. 测试配置语法:

    bash 复制代码
    sudo nginx -t

    如果显示 syntax is ok 和 test is successful,则继续下一步。

  4. 重载 Nginx:

    bash 复制代码
    sudo systemctl reload nginx
  5. 确保后端服务运行 :

    确保 localhost:8080 和 localhost:8081 上有实际的后端服务在运行,否则访问 API 时会返回 502 Bad Gateway。


4. 常见问题排查

现象 可能原因 解决方案
刷新页面 404 缺少 try_files 或 @router 配置 检查 location / 块中是否包含 try_files $uri $uri/ @router;
API 请求 404 proxy_pass 路径处理错误 检查 proxy_pass 后是否有斜杠,以及后端接口路径是否匹配
静态资源 403 文件权限不足 检查 /home/ubuntu/... 目录及文件是否对 www-data 用户可读
配置不生效 配置未重载或软链接错误 运行 sudo nginx -t 检查语法,确认 sites-enabled 中有对应的链接

总结

配置 Nginx 的核心在于理解请求流向:

  1. 静态文件:直接由 Nginx 提供(速度快)。
  2. 动态 API :通过 proxy_pass 转发给后端服务。
  3. SPA 路由 :通过 try_files 兜底回退到 index.html。

掌握这三点,你就能够应对 90% 以上的 Web 部署场景。希望这篇文章能帮助你更好地理解和使用 Nginx!如果有具体的报错信息,欢迎随时交流。

相关推荐
孤狼GPT1 天前
ChatGPT、Codex排查实录:接口偶发502/504,应用日志却没有报错,到底该查哪一层?
nginx·codex·chatgptplus·chatgptpro·接口排查
2601_962381132 天前
历史视频朝代更替动效怎么做?把 AE 关键帧换成 AI 分镜动画的实战拆解
人工智能·nginx·音视频
数据杂坛2 天前
【Python程序开发系列】一文搞清楚Gunicorn以及和Nginx的区别
python·nginx·gunicorn
锅巴编程2 天前
nginx-413-client-max-body-size
运维·nginx
cpolar技术支持2 天前
服务器上的 Nginx 只想改配置却不敢动?把 Nginx-UI 跑起来,用 MCP 让 AI 助手帮你安全改配置,再用 cpolar 把面板短时开给自己
nginx·ai·cpolar·mcp·nginx-ui
春天花会开1312 天前
内网 HTTPS 部署实战:私有 CA + Nginx 反向代理全流程复盘
运维·nginx·https
还是大剑师兰特8 天前
解决nginx错误:http://localhost:7000正常,http://localhost:7000/map 报错404
nginx·大剑师
xing-xing8 天前
Docker容器中Nginx站点根目录网页配置访问
nginx·docker
PC2005-cloud8 天前
Nginx 防盗链配置实战:用 referer 模块保护网站静态资源
nginx