【问题标题】:How can I remove and redirect all .php extensions, redirect "www", and remove trailing slashes?如何删除和重定向所有 .php 扩展名、重定向“www”以及删除尾部斜杠?
【发布时间】:2012-01-03 14:14:10
【问题描述】:

我一直在尝试从我网站上的所有页面中删除“.php”,同时还使用 .htaccess 从 URL 中删除所有尾部斜杠和“www”。我已经能够同时使用其中的一两个,但不是全部。我真的很感激任何帮助。

例如:

  • example.com/ 到 example.com
  • www.example.com 到 example.com
  • example.com/index 到 example.com
  • example.com/index.php 到 example.com
  • example.com/chatroom.php 到 example.com/chatroom
  • example.com/directory/ 到 example.com/directory

我想确保旧 URL 重定向到新 URL,并且我没有任何目录与 PHP 文件共享名称。在我的 .htaccess 文件中,我也有代码阻止特定的引用者并指定 403 和 404 错误。 非常感谢!

【问题讨论】:

    标签: php .htaccess mod-rewrite redirect


    【解决方案1】:

    Hide PHP using htaccess URL rewriting

    URL Rewriting for beginners

    How to do URL re-writing in PHP?

    URL Rewriting tool

    检查上面的网址。在这些教程中,您可以了解如何重写 URL。

    【讨论】:

    • 感谢您提供的链接,但我仍然对如何进行重定向感到非常困惑。他们并没有真正展示如何同时完成所有这些工作。
    • 要重写 URL,您应该在您的 web 目录的根文件夹中创建一个 .htaccess 文件。并且必须将以下代码作为您的要求。 Options +FollowSymlinks RewriteEngine on RewriteRule ^(.*)\.htm$ $1.php [nc] 你检查过这些行吗?您可以从任何站点下载 .htaccess 文件。
    【解决方案2】:

    我今天刚刚对尾部斜杠提出了同样的问题。这就是我最终在 .htaccess 文件中解决它的方式(重要的是 DirectorySlash 和第一个重写规则):

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    #Do not automatically add a slash for existing directories
    DirectorySlash Off
    
    
    #No trailing slash. This means that an URL entered with trailing / will change to an URL without trailing /
    #The !-d rule can be included so that any URLs to existing directories are not changed
    #RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
    
    #Allow URL's which do not have the php file extension
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^  %{REQUEST_FILENAME}.php [L]
    
    
    #Redirect any file which does not exist to the index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /index.php [R=301,L]
    
    </IfModule>
    

    因此,如果您键入 URL example.com/index/,它将重定向到 example.com/index。如果您输入 example.com/chatroom(并且存在一个 chatroom.php)它仍然在 URL 中有 example.com/chatroom 但您的 PHP 脚本会收到 example.com/chatroom.php

    您需要添加的是将 index.php 重定向到 / 和删除 www 的两种情况

    我所包含的(我不知道你是否需要它)是将任何不存在的文件重定向到 index.php 的最后一条规则

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 1970-01-01
      • 2014-06-21
      • 2012-07-01
      • 2017-07-14
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多