在 URL 末尾添加斜杠

在 URL 末尾添加斜杠

我最近更新了我的.htaccess文件隐藏.php 扩展名的网址。当我尝试访问domain.com/index,则显示php文件。

当我输入domain.com/index.php它会将我重定向到domain.com/indexurl 并显示 .php 文件。

出于安全原因,我想将所有其他扩展重定向到无扩展 url 以显示 .php 文件。我的问题是,我无法配置我的.htaccess重定向众所周知的扩展,例如.html .asp.aspx .shtml等到非扩展名的url,并获取显示为内容的.php文件。

我的.htaccess 文件如下所示:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# php extension to no extension url
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php $1 [R=301,L]


# no extension to the .php file
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

# this is for the index
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

答案1

在您的 .htaccess 文件中尝试这些,并请检查服务器上的重写引擎是否打开,以及主 apache conf 文件 httpd.conf 中是否有 mod_rewrite.c 模块。

1. RewriteRule ^about$ about.php [L] 或 2. RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)$ $1.php

希望这些能正常工作。

或者,否则这是具有所有描述的另一个选项:

Apache 重写规则选项 +FollowSymLinks RewriteEngine On RewriteBase /

在 URL 末尾添加斜杠

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.[a-zA-Z0-9]{1,5}|/|#(.))$ 重写规则^(.)$ $1/ [右=301,左]

从 URL 中删除 .php 扩展名

RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([^.]+)/$ $1.php

Apache 重写规则结束

我猜你想知道的事情:

  1. 这适用于不使用前端控制器的网站,所有请求都强制通过 index.php。如果您需要它,则必须用您自己的代码块替换第三个代码块。

  2. 该示例仅针对 .php 进行展示。例如,如果您想要将其用于 .html,则必须复制/粘贴第三个块,并将第 (1) 行和第 3 行和第 4 行的“.php”替换为“.html”(除非有人有巧妙的方法?)

  3. “example.com/something/” 的内容可以由“example.com/something.php”或“example.com/something/index.php”提供。

  4. 要链接到其他页面,只需 href=”/some/thing/” 或 href=”//example.com/some/thing/”。

  5. 使用 .css 和 .js 时,您需要 href=”/style.css” 或 href=”/folder1/style.css”。否则,如果您从“example.com/folder2/file.php” href=”style.css”,它将查找“example.com/folder2/style.css”。

注意:所有 example.com 前面都有 http://。

答案2

如果您的文件中除了扩展名之外没有其他“。”,您是否尝试用任何字符串替换“.php”?

# php extension to no extension url
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.\s+\sHTTP/.+
RewriteRule ^(.+)\.php $1 [R=301,L]

答案3

尝试下面的代码并更改您想要隐藏的扩展名:

1.对于 html 文件

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

2.对于php文件

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

相关内容