【问题标题】:How to replace dashes with slashes in .htaccess如何在 .htaccess 中用斜杠替换破折号
【发布时间】:2012-01-30 08:12:06
【问题描述】:

我想替换 PHP 文件名中的所有破折号,但我不知道该怎么做。

基本上我有这样的东西:

http://localhost/category-activity.php

我想结束这个:

http://localhost/category/activity

我还需要脚本扫描所有破折号,这意味着如果我有类似的东西:

http://localhost/category-activity-subactivity.php

以类似的方式结束:

http://localhost/category/activity/subactivity

我已经在使用下面的代码来移除扩展了

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

【问题讨论】:

    标签: .htaccess mod-rewrite replace


    【解决方案1】:

    试试这个:

    # not an existing directory and is a php file
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    # make sure there are no slashes and doesn't already end with .php
    RewriteCond %{REQUEST_URI} !^/.+/.+
    RewriteCond %{REQUEST_URI} !\.php$
    RewriteRule ^(.*)$ $1.php  [L]
    
    # not an existing directory or file (this needs to take place so existing paths won't get / replaced with -
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)/(.*)$ /$1-$2   [L]
    

    Mod-rewrite 将继续重新应用规则,直到 URI 没有被重写,所以像 /category/activity/subactivity 这样的 uri 将继续被重写,直到它通过所有未触及的规则。

    【讨论】:

    • 感谢您的帮助,但我似乎无法正常工作。我已经创建了一个 PHP 文件的链接,但 URL 显示了全名 + 扩展名。我也尝试过不使用扩展名或使用斜杠而不是破折号的链接,但它总是被重定向到我的 index.php。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2011-08-08
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多