【问题标题】:What is the rewrite rule to change www.domain.com to www.domain.com/es/?将 www.domain.com 更改为 www.domain.com/es/ 的重写规则是什么?
【发布时间】:2015-07-16 20:56:41
【问题描述】:

我的 htaccess 文件如下所示:

RewriteEngine On

# To add www at the beginning
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# To add / at the end
RewriteCond %{REQUEST_URI} !(/$|\.) 
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L] 

# Add /es/ at the end
RewriteCond %{REQUEST_URI} www.mydomain.com$ [NC]
RewriteRule (.*) %{REQUEST_URI}/es/ [R=301,L]

# Friendly URLs
RewriteRule ^([^/]*)/$ /?lang=$1 [L]
RewriteRule ^services/([^/]*)/$ /?services=$1 [L]
RewriteRule ^([^/]*)/services/([^/]*)/$ /?lang=$1&services=$2 [L]

# ErrorDocument 404 /web/page-404.php
# ErrorDocument 500 /web/page-500.php

我一直在尝试,但在键入 www.mydomain.com 时无法自动添加“/es/”。

目前,“#Add /es/ at the end”块正在添加“/es/?lang=es”。

一些帮助?谢谢!

【问题讨论】:

  • 不,添加?lang=es的不是那个块,而是下面的块。
  • 我需要下面的块将 www.mydomain.com/?lang=es 重定向到 www.mydomain.com/es/。此外,如果我使用我的“在末尾添加 /es/”规则并在下方评论该块,则不会发生任何事情。我怎么能两者兼得?谢谢
  • 对不起,没有。这个规则肯定会增加一个lang=es查询参数:RewriteRule ^([^/]*)/$ /?lang=$1 [L]
  • 是的,我见过。但我需要两个:www.mydomain.com 到 www.mydomain.com/es/ 和 www.mydomain.com/?lang=es 到 www.mydomain.com/es/。我的问题是......哪些是正确的重写规则,因为这些规则不起作用?
  • 再一次尝试:规则RewriteRule ^([^/]*)/$ /?lang=$1 [L]明确添加了lang=...查询参数。然而,在这个问题中,你问为什么会发生这种情况。答:你做。你为什么有这个规定?它不会www.mydomain.com/?lang=es 重写为www.mydomain.com/es/。我的印象是你并不真正了解这些规则是如何运作的。我建议你看看文档...httpd.apache.org/docs/current/mod/mod_rewrite.html

标签: .htaccess mod-rewrite url-rewriting


【解决方案1】:

试试这个规则:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteRule ^$ /es/ [R=301,L]

它重定向

example.com

example.com/es/

【讨论】:

    【解决方案2】:

    正如 cmets 中已经提到的问题,这些规则组合起来根本没有意义:

    # Add /es/ at the end
    RewriteCond %{REQUEST_URI} www.mydomain.com$ [NC]
    RewriteRule (.*) %{REQUEST_URI}/es/ [R=301,L]
    
    # Friendly URLs
    RewriteRule ^([^/]*)/$ /?lang=$1 [L]
    

    它们没有意义,因为这里发生的事情是这样的:第一个文件将任何传入请求重写为...../es/。然后下一条规则将该请求再次重写为.../es/?lang=es,因为第二条规则正则表达式采用es 并附加为查询参数lang=es,这正是您声称的想要的即将发生。

    那么第二条规则有什么用呢?去掉它!

    这很可能不是您的最终解决方案,因为我不知道您还想通过您的规则实现什么。这只是为了指出手头的问题......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2019-10-05
      • 1970-01-01
      • 2011-10-23
      • 2012-12-22
      • 2019-07-08
      相关资源
      最近更新 更多