使用.htaccess从URL中删除.php扩展名?

时间:2013-04-14 19:20:33

标签: php .htaccess friendly-url clean-urls

是否可以使用 .htaccess 文件从我的所有网址中删除.php部分?

两个例子:

http://url.com/home.php
http://url.com/shops.php

成为:

http://url.com/home/
http://url.com/shops/

所有帮助都将受到大力赞赏。

4 个答案:

答案 0 :(得分:4)

这应该有效:

RewriteEngine On
RewriteRule \/([^\/]+)\/$ $1.php

它将为您提供以url的最后一段命名的文件:

http://example.com/shops/shopname1/ - > shopname1.php

http://example.com/shops/ - > shops.php

答案 1 :(得分:3)

/ $ var / 重写为 / $ var.php ,然后将 / $ var.php 重定向到 / $ var / 只需在 .htaccess 文件中使用这些指令:

# once per htaccess file
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-_]+)/? /$1.php
RewriteRule ^([a-z0-9-_]+).php$ /$1/ [R]

如果您还想将特定网址 / shops / shopName1 / 重写为特定网址 /shopName1.php ,然后重定向 /shopName1.php 进入 / shops / shopName1 / 然后你应该使用下面的代码代替上面的代码:

# once per htaccess file
Options +FollowSymlinks
RewriteEngine on

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

RewriteCond %{REQUEST_URI} !^/shopName1.php$
RewriteRule ^([a-z0-9-_]+).php$ /$1/ [R]

RewriteRule ^shops/shopName1/?$ /shopName1.php
RewriteRule ^shopName1.php$ /shops/shopName1/ [R]

但请记住 / shops / shopName1 / 上没有变量,试试看,如果你想要的话......


使用DirectoryIndex home.php进行重定向似乎存在问题。但我想,这是你想要的代码,但在这个时候,我们排除了任何重定向:

DirectoryIndex /home.php
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/shopName1/?$
RewriteCond %{REQUEST_URI} !^/shopName2/?$
RewriteCond %{REQUEST_URI} !^/shopName3/?$
RewriteCond %{REQUEST_URI} !^/shopName4/?$
RewriteCond %{REQUEST_URI} !^/shopName5/?$
RewriteRule ^([a-zA-Z0-9-_]+)/?$ /$1.php

RewriteRule ^shops/shopName1/?$ /shopName1.php
RewriteRule ^shops/shopName2/?$ /shopName2.php
RewriteRule ^shops/shopName3/?$ /shopName3.php
RewriteRule ^shops/shopName4/?$ /shopName4.php
RewriteRule ^shops/shopName5/?$ /shopName5.php

只需使用您的逻辑添加更多条件和规则..

答案 2 :(得分:1)

我建议简单地停止使用常规.php文件来代替页面而不是框架或请求路由器,但是如果你真的想这样做,那么为了shops.php到{{1你需要创建一个.htaccess文件并添加以下内容:

shops

这会将网址栏上的所有RewriteRule (.*) $1.php [L] 重命名为something.php

完整something文件的示例如下:

.htaccess

答案 3 :(得分:0)

RewriteRule ^/(home|shops) /$1.php

仅限第二手册

RewriteRule ^/shops/shopname1/ /whateveryouneed.php