【问题标题】:Url rewriting and folders网址重写和文件夹
【发布时间】:2013-01-25 02:01:39
【问题描述】:

我的网站有一个子目录:

http://www.mysite.com/test/

在我的“测试”目录中:

index.php
included-inside-index-file.php
another-included-inside-index-file.php
script.php

现在,我怎样才能用 .htaccess 重写 url,使它像这样工作:

http://www.mysite.com/test --> access index.php
http://www.mysite.com/test/beautiful-url --> access script.php?parameter=beautiful-url
http://www.mysite.com/test/included-inside-index-file.php --> 404 error
http://www.mysite.com/test/another-included-inside-index-file.php --> 404 error

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    这很简单。您需要为 beautiful-url 制定一个通用规则,但前面有一些规则,该规则会为您要隐藏的脚本抛出 [R=404,L]

    RewriteEngine On
    
    # First hide the includes
    # These could be simplified if they follow a pattern.
    # Here we'll list them individually though.
    RewriteRule ^test/included-inside-index-file\.php - [R=404,L]
    RewriteRule ^test/another-included-inside-index-file\.php - [R=404,L]
    
    # Then rewrite to the beautiful URL if the file doesn't exist.
    # The index.php will serve normally because it does exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^test/(.+)$ test/script.php?parameter=$1 [L]
    

    如果您想明确阻止对script.php 的直接访问,您可以在THE_REQUEST 中匹配它。将其放在阻止访问包含的规则之后。我认为这行得通。如果您尝试在没有RewriteCond 的情况下执行此操作,您会从漂亮的 url 重写中得到 404。

    RewriteCond %{THE_REQUEST} script\.php
    RewriteRule ^. - [R=404,L]
    

    【讨论】:

    • 谢谢!这应该工作!一旦我测试它,我会标记你的答案是正确的。
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2010-10-08
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多