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

Azure WebApp中使用Nginx将所有请求重定向至/public文件夹

解决方案

方法1:通过Nginx的conf.d目录添加持久化自定义配置

Nginx默认会自动加载/etc/nginx/conf.d/目录下所有.conf后缀的配置文件,这个目录的修改通常是持久的,不会被系统重置。

  • 创建自定义配置文件:

    sudo touch /etc/nginx/conf.d/redirect-to-public.conf
    
  • 编辑该文件,根据实际需求选择以下配置之一:
    场景A:直接将网站根目录指向/public文件夹

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        root /absolute/path/to/public; # 替换为你的/public文件夹绝对路径
        index index.html index.htm;
    
        server_name _;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

    场景B:将所有请求内部重定向到/public子目录(保留原根目录结构)

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        root /original/root/path; # 替换为网站原来的根目录路径
        index index.html index.htm;
    
        server_name _;
    
        # 将所有请求转发到/public子目录
        location / {
            rewrite ^/(.*)$ /public/$1 last;
        }
    
        # 处理/public目录的实际文件请求
        location /public/ {
            try_files $uri $uri/ =404;
        }
    }
    
  • 重启Nginx使配置生效:

    sudo systemctl restart nginx
    

方法2:容器化环境下的持久化配置(如Docker)

如果你的Nginx运行在容器中,默认配置会随容器重置,可通过宿主机挂载配置文件的方式实现持久化:

  • 在宿主机创建自定义配置文件(路径如/host/config/redirect-to-public.conf),写入方法1中的Nginx配置
  • 启动容器时挂载该文件:
    docker run -d -p 80:80 -v /host/config/redirect-to-public.conf:/etc/nginx/conf.d/redirect-to-public.conf nginx
    

方法3:使用.htaccess(不推荐,仅兼容场景)

若你有权限在网站根目录创建.htaccess文件,且Nginx启用了mod_rewrite兼容,可添加以下内容:

RewriteEngine On
RewriteRule ^(.*)$ /public/$1 [L]

同时需确保Nginx的server配置块中允许读取.htaccess:

location / {
    allow override all;
}

注:此方法性能低于直接Nginx配置,仅在无法使用前两种方法时考虑

内容的提问来源于stack exchange,提问作者Roger Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:06:11