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

Laravel站点未设语言时重定向至默认英文路径的.htaccess配置需求

解决Laravel站点默认语言前缀重定向问题

需求说明

站点example.com默认语言为英语(en),要求所有未携带语言参数的请求,自动重定向到带/en/前缀的对应路径,示例:

  • 原请求:example.com/blogpost/thisisapost → 重定向至:example.com/en/blogpost/thisisapost
  • 原请求:example.com/one/two/three/etc → 重定向至:example.com/en/one/two/three/etc

现有.htaccess配置

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

修改后的.htaccess配置

在「Handle Authorization Header」规则之后、「Redirect Trailing Slashes」规则之前,添加默认语言前缀的重定向规则,完整配置如下:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect requests without language prefix to default (en)
    RewriteCond %{REQUEST_URI} !^/en/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /en/$1 [L,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

规则说明

  • RewriteCond %{REQUEST_URI} !^/en/:排除已经带有/en/前缀的请求,防止循环重定向
  • RewriteCond %{REQUEST_FILENAME} !-f 和 RewriteCond %{REQUEST_FILENAME} !-d:排除真实存在的文件和目录,避免静态资源(如图片、CSS、JS)被错误重定向
  • RewriteRule ^(.*)$ /en/$1 [L,R=301]:将所有符合条件的请求重定向到带/en/前缀的路径,R=301表示永久重定向(利于SEO),L表示这是当前匹配的最后一条规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:27:27