【问题标题】:Rewriting directory name to php script name - but allow ending slash将目录名称重写为 php 脚本名称 - 但允许以斜线结尾
【发布时间】:2015-03-17 02:39:26
【问题描述】:

是的,我已经阅读了关于 SO 的其他类似问题,这就是我想出这个可能的解决方案的方式:

# Turn on the mod_rewrite engine
RewriteEngine On

# IF the request filename with .php extension is a file which exists
RewriteCond %{REQUEST_FILENAME}.php -f

# AND the request is not for a directory
RewriteCond %{REQUEST_URI} !/$

# Redirect to the php script with the requested filename
RewriteRule (.*) $1\.php [L]

这可以通过重写请求来实现,例如:/about-usabout-us.php,但是如果你转到 /about-us/,它不起作用

我尝试了以下方法,但没有成功:

# Redirect to the php script with the requested filename
RewriteRule (.*)/? $1\.php [L]

和第二个RewriteCond有关系吗?

基本上,如果请求是针对真实文件或目录的,我希望它失败(如果可能),但如果两者都不存在,那么无论请求是否有结束斜杠,它都应该重写为 PHP 脚本。

这个可以吗?

【问题讨论】:

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


    【解决方案1】:

    这样制定你的规则:

    当 .htaccess 和 .php 文件位于子目录中时,请使用:

    RewriteEngine On 
    
    RewriteCond %{DOCUMENT_ROOT}/work/Client_Name/public_html/$1\.php -f [NC] 
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    当 .htaccess 和 .php 文件直接位于站点根目录时,请使用:

    RewriteEngine On 
    
    RewriteCond %{DOCUMENT_ROOT}$1\.php -f [NC] 
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    【讨论】:

    • 这可能是因为我正在开发机器上的子目录中工作?
    • 嗯,更新后的规则没有结尾斜杠有效,但没有它。
    • 它是位于名为public_html 的目录中的根目录之外的 3 个目录。我们可以设置RewriteBase 吗?
    • 是的,这就是为什么我想知道你的子目录路径相对于public_html
    • 这将是../../../ 到来自public_html 的“网络根目录”。但是目录public_html 是这个特定站点的根目录。然后文件将位于/public_html/about-us.php 并通过public_html/about-us/ 请求。
    猜你喜欢
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多