![](/img/trans.png)
[英]URL rewrite with .htaccess for multiple-language site (multiple variables)
[英]URL rewrite with HTACCESS for multiple language support
我希望為我的網站添加多語言支持。 是否可以使用.htaccess
文件來更改以下內容:
example.com/dir/?lang=en
到example.com/en/dir/
example.com/main/?lang=de
到example.com/de/main/
example.com/main/page.php?lang=de
to example.com/de/main/page.php
這適用於任何可能的目錄 - 所以如果稍后我創建了一個新目錄,我不需要添加到這個目錄。 在上面的示例中,我希望后者成為用戶在地址欄中輸入的內容,並開始成為內部使用的方式。
是否可以使用
.htaccess
文件來更改以下內容:
example.com/dir/?lang=en
到example.com/en/dir/
是的,除非您沒有在.htaccess
中將 URL 更改為example.com/en/dir/
。 在您更改 .htaccess 中的任何內容之前,您在應用程序的內部鏈接中將.htaccess
更改為example.com/en/dir/
。 這是規范的 URL 並且是“用戶在地址欄中輸入的內容” - 正如您所說。
然后,您使用.htaccess
在內部重寫來自example.com/en/dir/
的請求,回到您的應用程序理解的 URL 中,即。 example.com/dir/?lang=en
(或者更確切地說是example.com/dir/index.php?lang=en
- 見下文)。 這對用戶完全隱藏。 用戶只看到example.com/en/dir/
- 即使他們查看 HTML 源。
因此,我們需要將/<lang>/<url-path>/
重寫為/<url-path>/?lang=<lang>
。 其中<lang>
假定為 2 個字符的小寫語言代碼。 如果您只提供一小部分語言選擇,則應明確說明以避免沖突。 我們還可以處理原始請求上的任何附加查詢字符串(如果需要)。 例如。 /<lang>/<url-path>/?<query-string>
到/<url-path>/?lang=<lang>&<query-string>
。
這里的一個小問題是/dir/?lang=en
形式的 URL 嚴格來說不是有效的端點,需要進一步重寫。 我希望您依靠 mod_dir 為 DirectoryIndex 發出內部子請求,例如。 index.php
? 所以,真的,這應該直接重寫為/dir/index.php?lang=en
- 或者 DirectoryIndex 文檔定義的任何內容。
例如,在您的根.htaccess
文件中:
RewriteEngine On
# Rewrite "/<lang>/<directory>/" to `/<directory>/index.php?lang=<lang>"
RewriteCond %{DOCUMENT_ROOT}/$2/index.php -f
RewriteRule ^([a-z]{2})/(.*?)/?$ $2/index.php?lang=$1 [L]
# Rewrite "/<lang>/<directory>/<file>" to `/<directory>/<file>?lang=<lang>"
RewriteCond %{DOCUMENT_ROOT}/$2 -f
RewriteRule ^([a-z]{2})/(.+) $2?lang=$1 [L]
如果您只有兩種語言(如您的示例中所示),或已知語言的一小部分,則更改([az]{2})
子模式以使用交替並明確標識每種語言代碼,例如。 (en|de|ab|cd)
。
這確實假設您在文檔根目錄中沒有包含 2 個小寫字母(或匹配特定語言代碼)的物理目錄。
僅重寫目標目錄(包含index.php
)或文件存在的 URL。
這還將重寫對文檔根的請求(在您的示例中未明確說明)。 例如。 example.com/en/
(此處需要斜杠)被重寫為/index.php?lang=en
。
如果對目錄的請求始終包含尾部斜杠,則正則表達式的效率可能會稍高一些。 在上面我假設尾部斜杠是可選的,盡管這可能會產生重復的內容問題,除非您以其他方式解決此問題(例如rel="canonical"
鏈接元素)。 因此,在上面的代碼中, example.com/en/dir/
/en/dir/(斜杠)和example.com/en/dir
(無斜杠)都可以訪問並且都返回相同的資源,即。 /dir/index.php?lang=en
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.