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

Nginx配置需求:无语言标识URL重定向至默认语言it

Nginx 特定域名默认语言重定向配置方案

需求说明

  • 系统全局默认语言为德语(locale=de),即domain.com/...默认指向德语内容
  • 针对某一特定域名,需将默认语言改为意大利语(it),且无法通过CMS修改该域名默认语言
  • 实现目标:
    • 当URL未包含语言标识时(如domain.com/...),自动重定向到domain.com/it/...
    • 包含/de、/en语言标识的URL保持不变,不触发重定向

修改后的Nginx配置

将重定向规则添加到对应域名的server块最前端,完整配置如下:

server {
    server_name your-specific-domain.com; # 替换为需要设置默认意大利语的目标域名

    # 新增:无语言标识的请求重定向至/it/路径
    # 排除已有的语言路径、静态资源及特殊文件
    if ($request_uri !~ ^/(de|en|_Resources|favicon\.ico|robots\.txt)/) {
        # 根路径直接跳转到/it/
        if ($request_uri = '/') {
            return 301 /it/;
        }
        # 其他路径在原路径前添加/it/前缀
        rewrite ^/(.*)$ /it/$1 permanent;
    }

    # 以下是原有的配置内容
    location ~ /\. {
        access_log off;
        log_not_found off;
        deny all;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ /_Resources/ {
        access_log off;
        log_not_found off;
        expires max;

        if (!-f $request_filename) {
            rewrite "/_Resources/Persistent/([a-z0-9]{40})/.+\.(.+)" /_Resources/Persistent/$1.$2 break;
            rewrite "/_Resources/Persistent(?>/[a-z0-9]{5}){8}/([a-f0-9]{40})/.+\.(.+)" /_Resources/Persistent/$1.$2 break;
        }
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include /usr/local/etc/nginx/fastcgi_params;
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.socket;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param FLOW_REWRITEURLS 1;
        fastcgi_param FLOW_CONTEXT Production;
        fastcgi_param FLOW_ROOTPATH /var/www/public_html/current/;
        fastcgi_param X-Forwarded-For $proxy_add_x_forwarded_for;
        fastcgi_param X-Forwarded-Port $proxy_port;
        fastcgi_param SERVER_NAME $http_host;
        fastcgi_param SERVER_PORT 443;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

规则说明

  1. 域名匹配:通过server_name指定需要生效的特定域名,确保规则只作用于目标站点,不影响其他域名
  2. 排除规则:第一个if条件过滤掉已有语言标识(/de/、/en/)、静态资源目录(_Resources)和特殊文件(favicon.ico、robots.txt),这些请求不会触发重定向
  3. 重定向逻辑:
    • 访问根路径/时,直接返回301重定向到/it/
    • 访问其他无语言标识的路径时,自动在路径前添加/it/前缀,使用permanent(301永久重定向),符合SEO最佳实践
  4. 执行顺序:重定向规则必须放在所有location块之前,确保Nginx优先匹配执行该规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:35:36