【问题标题】:Apache .htaccess file not rewriting properlyApache .htaccess 文件未正确重写
【发布时间】:2015-05-21 19:37:14
【问题描述】:

我有一个 .htaccess 文件。它需要在两种情况下重写 URL:对于 MVC 框架和更特殊的情况。如果用户没有名为“cfnw-hash”的 cookie,我想重写对“/resources/newspaper”的任何请求。我尝试将代码放在 MVC 代码之前和之后。不工作。它在切换到 MVC 框架之前工作,虽然我真的没有足够的 .htaccess 知识来查看是否导致问题。代码如下:

Options -Indexes

<IfModule mod_rewrite.c>
    Options -Indexes

    RewriteEngine On
    RewriteBase /

    # Force to exclude the trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.*)/$
    RewriteRule ^(.+)/$ $1 [R=307,L]

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cfnw-hash [NC]
RewriteRule \/resources\/newspaper.* http://www.example.com/error/401 [R=401,NC,L]

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite cookies


    【解决方案1】:

    这样吧:

    <IfModule mod_rewrite.c>
        Options -Indexes
    
        RewriteEngine On
        RewriteBase /
    
        RewriteCond %{HTTP_COOKIE} !cfnw-hash [NC]
        RewriteRule ^resources/newspaper /error/401 [R=401,NC,L]    
    
        # Force to exclude the trailing slash
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.*)/$
        RewriteRule ^(.+)/$ $1 [R=307,L]
    
        # Allow any files or directories that exist to be displayed directly
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d    
        RewriteRule ^(.*)$ index.php?$1 [QSA,L]
    </IfModule>
    

    清除浏览器缓存后进行测试。

    【讨论】:

      【解决方案2】:

      结合你的规则,我认为你的 RewriteRule 可能不匹配,因为前面的 / 和 cookie 匹配。尝试这个。请注意您使用 cookie 更新的 cookie 部分。

      Options -Indexes
      
      <IfModule mod_rewrite.c>
      
          RewriteEngine On
          RewriteBase /
      
          RewriteCond %{HTTP_COOKIE}  !cookie_name=specific_value; [NC]
          RewriteRule ^resources/newspaper/?(.*) http://www.example.com/error/401 [R=401,NC,L]
      
          # Force to exclude the trailing slash
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_URI} (.*)/$
          RewriteRule ^(.+)/$ $1 [R=307,L]
      
          # Allow any files or directories that exist to be displayed directly
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_FILENAME} !-d
      
          RewriteRule ^(.*)$ index.php?$1 [QSA,L]
      </IfModule>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-04
        • 2011-01-02
        • 2015-07-18
        • 1970-01-01
        • 2012-03-07
        • 2010-11-09
        • 1970-01-01
        相关资源
        最近更新 更多