使用 .htaccess 切换语言

Switching language with .htaccess

我想为我的网站添加另一种语言(用 PHP 7 编写的应用程序)。 我发现,良好的 SEO 实践表明,我网站上的每个页面都应该可以从不同的 URL 访问,具体取决于语言。

目前我的 .htaccess 看起来像这样:

RewriteEngine on
Options +FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([a-zA-z0-9-]+)$ .php [NC,L]

因此,当用户输入(或单击 link)http://example.com/contact 时,他们将获得页面 contact.php(如果存在)。 我想要实现的是,将 http://example.com/en/contact 重定向到同一个文件 contact.php,但使用 $_GET 参数 并且仍然将 /contact 重定向到 contact.php(没有这个论点)。我以为会是:

... everything from above code sample and then:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^en/([a-zA-z0-9-]+)$ .php?lang=en [NC,L]

但是没用。为什么以及如何使这项工作有任何想法?

最后一个条件检查 en/file.php 是否存在,但事实并非如此。这就是为什么永远不会满足规则的原因。要么删除它(但它甚至会应用于不存在的文件),要么通过重写错误条件来使用此解决方法

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/\.php -f
RewriteRule ^en/([^/]+)$ /.php?lang=en [NC,L]

为了更完整,您还可以重定向尝试直接访问 /contact.php?lang=en 的用户(更利于 SEO)。这是您最终的 htaccess 的样子

RewriteEngine On

# if url is /file.php?lang=en and file exists then redirect to /en/file
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s/([^/\s\?&]+)\.php\?lang=en\s [NC]
RewriteRule ^ /en/%1? [R=301,L]

# if url is /en/file and /file.php exists then internally rewrite to /file.php?lang=en
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/\.php -f
RewriteRule ^en/([^/]+)$ /.php?lang=en [NC,L]

注意:以上代码特定于en语言,但您可以轻松将其适配到多种语言