【问题标题】:Merging a few Mod Rewrite Rules合并一些 Mod 重写规则
【发布时间】:2012-09-27 17:56:46
【问题描述】:

这更像是对这个问题的后续问题: .htaccess - how to force "www." in a generic way?

我有这个规则:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

我想将它们与该答案中提供的合并:

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

这些是正确的结果(正确的顺序和规则)吗?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

到目前为止,一切都按预期进行,但我的所有测试都是在临时 URL 中完成的,而不是在实际域中完成的。

谢谢!

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    这些规则应该可以满足您的需求,但我会稍微调整一下。既然你有什么作品,这只是基于我的喜好的建议。 :)

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php/$1 [L]
    </IfModule>
    

    我发现当所有不是规则的重写选项都排在第一位时会更容易阅读。我还喜欢添加空行,以便更容易查看一组规则的结束位置和下一组规则的开始位置。

    此规则是不必要的:RewriteRule ^index\.php$ - [L],因为下一条规则只会影响对未映射到真实文件的 URI 的请求。因为文件系统上存在index.php,所以不会触发下一条规则。

    对于 index.php 规则,添加 /$1 会使请求在 $_SERVER['PATH_INFO'] 中可用,这取决于您的代码的编写方式,这可能会有所帮助。这绝对不是必需的,但是对于像 WordPress 或 CodeIgniter 这样的应用程序来说,建议这种方法很常见,所以我认为值得一提。

    【讨论】:

      猜你喜欢
      • 2010-11-13
      • 2012-05-13
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多