【问题标题】:mod_rewrite: dynamic redirect and directory blockingmod_rewrite:动态重定向和目录阻塞
【发布时间】:2014-02-09 16:03:52
【问题描述】:

我正在处理位于 mysite.com/dir/.htaccess 中的 .htaccess 文件,如果可能,该文件会将 mysite.com/dir/page 重定向到 mysite.com/dir/page.php 并重定向到 mysite.com/ dir/ 如果不可能的话。所以任何“错误”的请求都会被重定向到主页。我使用的代码是:

RewriteEngine on

# determine DIR_BASE dynamically
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=DIR_BASE:%1]

# see if .php is found
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f
RewriteRule ^(.*)$ $1.php

# if not found redirect to %{ENV:DIR_BASE}
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ %{ENV:DIR_BASE} [R]

这一切都很好。 (顺便说一句:我想确定文件的基本目录,因为我以后可能想更改目录名称,但不更改文件)。我现在想要的是为用户阻止一些目录,因为它们包含不应访问的 php 库。我怎么能像以前一样阻止目录 mysite.com/dir/lib/* 和 mysite.com/dir/lib2/* 并再次将它们重定向到 mysite.com/dir/?我也想用不喜欢的代码

RewriteRule ^lib/(.)* %{ENV:DIR_BASE}

这会将 mysite.com/dir/lib/../page 重定向到主页,而不是它应该属于的 mysite.com/dir/page。我对 %{REQUEST_FILENAME} 和 %{REQUEST_URI} 进行了很多尝试,但在 mod_rewrite 方面我只是一个初学者。你知道解决办法吗?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite redirect


    【解决方案1】:

    这应该可行:

    RewriteEngine on
    
    # determine DIR_BASE dynamically
    RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
    RewriteRule ^(.*)$ - [E=DIR_BASE:%1]
    
    RewriteRule ^lib2?(/|$) %{ENV:DIR_BASE} [L,NC,R]
    
    # see if .php is found
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f [NC]
    RewriteRule ^(.*)$ $1.php [L]
    
    # if not found redirect to %{ENV:DIR_BASE}
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ %{ENV:DIR_BASE} [L,R]
    

    【讨论】:

    • 是的,效果很好,非常感谢。这不是你第二次为我回答问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多