【问题标题】:.htaccess redirect if file exists.htaccess 如果文件存在则重定向
【发布时间】:2011-09-12 11:27:34
【问题描述】:

我希望使用 .htaccess 根据目录中是否存在文件来重定向到一个页面或另一个页面。

基本上,如果 splash.php 不存在,我需要将 index.php 的所有访问者发送到 home.php 页面,或者如果 splash.php 存在,我需要将所有访问者发送到 splash.php 页面strong> 存在于目录中,目前我有这个...

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} index.php
RewriteCond %{DOCUMENT_ROOT}/splash.php -f
RewriteCond %{SCRIPT_FILENAME} !splash.php
RewriteRule ^.*$ /splash.php [L]

只有当我明确将 mysite.com/index.php 作为我的 URL 时,它才会将访问者发送到 mysite.com/splash.php,如果只使用 mysite.com URL,它将不起作用。

我了解我的代码的前 3 行,但不了解 !splash.php -f 位(我是从我在 SO 上找到的其他重定向代码中得到的)。

如果 splash.php 不存在,我如何重定向到 home.php?

干杯!

【问题讨论】:

    标签: php apache .htaccess mod-rewrite redirect


    【解决方案1】:

    试试这个规则。它应该适用于 mysite.com/index.php、mysite.com/ 或 mysite.com

    RewriteEngine on
    RewriteCond %{DOCUMENT_ROOT}/splash.php -f
    RewriteCond %{SCRIPT_FILENAME} !splash.php
    RewriteRule ^(index\.php|/|)$ /splash.php [L]
    

    【讨论】:

    • 在你的正则表达式中有一个额外的|
    • 这是一个梦寐以求的伙伴,谢谢!只要我设置 DirectoryIndex = home.php
    • @Salman - 额外 |是故意的(也匹配一个空字符串)
    【解决方案2】:

    你需要把它分成多个块,所以试试这个(如果它存在就去splash.php,不管文件名中是否有index.php,然后如果splash不存在转到 home.php):

    RewriteEngine on
    
    RewriteCond %{DOCUMENT_ROOT}/splash.php -f
    RewriteCond %{SCRIPT_FILENAME} !splash.php
    RewriteRule ^.*$ /splash.php [L]
    
    RewriteCond %{DOCUMENT_ROOT}/splash.php !-f
    RewriteRule ^.*$ /home.php [L]
    

    【讨论】:

    • 这看起来真的应该有效,我现在“明白了”。但它只是抛出一个 500 内部错误
    • 啊,可能缺少 RewriteBase 或其他类似设置。
    【解决方案3】:

    伙计,我添加了一个快速的 .htaccess,它对我来说非常有效。不过,我不确定您的配置可能有什么不同。为避免混淆,这是我正在使用的 Apache (2) vhost:

    <VirtualHost *:80>
       DocumentRoot "/usr/local/zend/apache2/htdocs/test-setup"
       ServerName test-setup
       ErrorLog /var/log/apache2/lps-version-one_test-setup_error_log
       LogLevel warn
       CustomLog /var/log/apache2/lps-version-one_test-setup_access_log combined
        <Directory "/usr/local/zend/apache2/htdocs/test-setup">
            DirectoryIndex index.php
            AllowOverride All 
            Order allow,deny
            Allow from all 
        </Directory>
    </VirtualHost>
    

    当我在目录中有两个文件时,我被重定向到 splash.php(即使 url 中的文件名没有改变 - 在内部我被重定向到 splash.php)。当我重命名 splash.php(或删除它)时,我只看到 index.php。当我把它放回去时,重定向正常工作。当我专门将 index.php 放在 url 中时,两个文件都可用,我被重定向到 splash.php。

    Fwiw,关于 mod_rewrite 最好记住的事情之一是:

    尽管有大量的示例和文档, mod_rewrite 是巫毒教。该死的酷 巫毒,但仍然是巫毒。 -- 布莱恩·摩尔 bem@news.cmc.net

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 2010-10-14
      • 2016-02-28
      • 1970-01-01
      相关资源
      最近更新 更多