You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用SSL后Nginx仅提供首页,其他页面报404问题排查求助

Nginx HTTPS配置后仅首页可访问的问题排查与解决

问题场景

基于nginx:alpine Docker镜像配置SSL后,UI静态内容存放于/usr/share/nginx/html目录。HTTP协议下所有页面可正常加载,但启用HTTPS后仅能访问首页,其余页面均返回Nginx默认的404 Not Found错误。服务器不存在sites-available目录,推测为配置疏漏,附上相关配置文件:

/etc/nginx/conf.d/default.conf

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name _;
  return 301 https://$host$request_uri;
}
server {
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;
  ssl_certificate /etc/nginx/certificate/nginx-certificate.crt;
  ssl_certificate_key /etc/nginx/certificate/nginx.key;
  server_name _;
  location / {
    root /usr/share/nginx/html;
      index index.html index.htm;
  }
  location /api {
    proxy_pass https://my-aws-ec2-instance.com;
  }
  location /em {
    proxy_pass https://my-aws-s3-instance.com;
  }
}

/etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

问题原因与解决方案

核心原因

该问题通常出现在**前端单页应用(SPA)**场景中:前端框架(如React、Vue)采用history模式路由时,非首页的URL(如/about)并非服务器上真实存在的物理文件。Nginx默认会尝试在/usr/share/nginx/html目录下查找对应路径的文件,找不到则返回404错误。

修复步骤

修改HTTPS server块中的location /配置,添加try_files $uri $uri/ /index.html;规则,让Nginx在找不到对应文件时,自动转发请求到首页index.html,由前端路由系统处理URL:

修改后的/etc/nginx/conf.d/default.conf中HTTPS server块如下:

server {
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;
  ssl_certificate /etc/nginx/certificate/nginx-certificate.crt;
  ssl_certificate_key /etc/nginx/certificate/nginx.key;
  server_name _;
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html; # 新增该行
  }
  location /api {
    proxy_pass https://my-aws-ec2-instance.com;
  }
  location /em {
    proxy_pass https://my-aws-s3-instance.com;
  }
}

验证方法

修改配置后,重启Nginx容器:

docker restart <your-nginx-container-name>

访问非首页URL,确认页面可正常加载。

内容的提问来源于stack exchange,提问作者Shashi Ranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:40:24