【问题标题】:Apache .htaccess to redirect all URLs except for files and directoriesApache .htaccess 重定向除文件和目录之外的所有 URL
【发布时间】:2015-06-27 20:10:23
【问题描述】:

我正在开发一个当前位于子域的网站。在 .htaccess 文件中,我有以下内容:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^([a-zA-Z_\-]+)/?$ /index.php?url=$1 [L,NC]
RewriteRule ^([a-zA-Z_\-]+)/(.+)/?$ /index.php?url=$1&$2 [L,NC]

当我尝试加载现有的 css 文件时,例如http://subdomain/path/to/existing/file.css Apache 仍然将其重定向到 index.php。除了现有文件和目录,是否可以将所有 URL 重定向到 index.php?

【问题讨论】:

    标签: apache .htaccess redirect


    【解决方案1】:

    您的代码的问题是最后一条规则没有条件,因为每个条件或一组条件只能有一个 RewriteRule

    很可能有更好的方法来做到这一点(也许使用跳过标志S),但您可以同时重复您的条件。

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    
    RewriteRule ^([a-z_-]+)/?$ index.php?url=$1 [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    
    RewriteRule ^([a-z_-]+)/(.+)/?$ index.php?url=$1&$2 [L,NC]
    

    此外,由于您已指定 NC 标志,因此您无需在模式中指定 A-Z。此外,无需转义连字符-

    更新:您也可以尝试设置一个环境变量,根据this answer

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    
    # If the conditions above are true, then set a variable to say so
    # and continue. 
    RewriteRule ^ - [E=TRUE:YES]
    
    RewriteCond %{ENV:TRUE} = YES
    RewriteRule ^([a-zA-Z_\-]+)/?$ /index.php?url=$1 [L,NC]
    
    RewriteCond %{ENV:TRUE} = YES
    RewriteRule ^([a-zA-Z_\-]+)/(.+)/?$ /index.php?url=$1&$2 [L,NC]
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 2012-04-06
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多