2012-04-05 135 views
15

我想要的东西,把我的.htaccess文件,将隐藏我的PHP文件.php文件扩展名,所以要www.example.com/dir/somepage会告诉他们www.example.com/dir/somepage.php。如何使用.htaccess隐藏.php网址的扩展名?

对此有任何可行的解决方案?我的网站使用HTTPS,如果这很重要的话。

这是我此刻的.htaccess:

RewriteEngine On 

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L] 

ErrorDocument 404 /error/404.php 

RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteCond %{REQUEST_URI} !/$ 
RewriteRule (.*) $1\.php [L] 
+0

重复:http://stackoverflow.com/a/1760412/209139 – TRiG 2012-04-05 12:01:29

回答

38

使用此代码在您的.htaccess下DOCUMENT_ROOT:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 
RewriteBase/

# To externally redirect /dir/foo.php to /dir/foo 
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] 
RewriteRule^%1 [R,L,NC] 

## To internally redirect /dir/foo to /dir/foo.php 
RewriteCond %{REQUEST_FILENAME}.php -f [NC] 
RewriteRule^%{REQUEST_URI}.php [L] 
+1

如何排除页面?这似乎是干扰我的登录脚本,所以我想从这些重写中排除该页面 – ChristopherStrydom 2014-08-08 14:02:02

+0

通常,您可以添加'RewriteCond%{REQUEST_URI}!^ /(page1 | page2)'类型条件。 – anubhava 2014-08-08 14:21:08

+0

谢谢你会试试看。我认为正在发生的是当页面被重新加载而没有扩展时它将丢失变量。有没有办法来解决这个问题?就好像它登录了两次......我想......一次用电子邮件通过,然后再次没有。所以我在所有我不能登录 – ChristopherStrydom 2014-08-08 14:30:06

0

试试这个:

# Unless directory, remove trailing slash 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L] 

# Redirect external .php requests to extensionless url 
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/ 
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L] 

# Resolve .php file for extensionless php urls 
RewriteRule ^([^/.]+)$ $1.php [L]Try: 

参考:

How to hide .php extension in .htaccess

+0

这不工作对我来说,很遗憾。 – Markum 2012-04-05 11:55:27

+0

然后尝试上面的代码。 – 2012-04-05 12:00:01

+0

仍然无法正常工作。 – Markum 2012-04-05 12:05:39

2
<IfModule mod_rewrite.c> 
RewriteEngine on 

RewriteCond %{REQUEST_FILENAME} !-f  # if the requested URL is not a file that exists 
RewriteCond %{REQUEST_FILENAME} !-d  # and it isn't a directory that exists either 
RewriteCond %{REQUEST_FILENAME}\.php -f # but when you put ".php" on the end it is a file that exists 
RewriteRule ^(.+)$ $1\.php [QSA]   # then serve that file (maintaining the query string) 

</IfModule> 

奇怪的是,这个代码GA在Windows中的XAMPP中尝试使用HTTP 500错误。删除评论修复了它。所以,移动评论,以便他们在他们自己的路线,而不是在指令相同的路线。

+1

试过这个,它给了我一个500错误。 – Markum 2012-04-05 12:10:37

+1

奇数。这个对我有用。 – TRiG 2012-04-05 12:13:57

+1

@Markum。从那以后,我发现一些实现不像代码那样喜欢评论。尝试删除评论。 – TRiG 2014-03-15 11:24:27

4

删除PHP扩展

您可以使用代码/.htaccess:

RewriteEngine on 


RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule^%{REQUEST_FILENAME}.php [NC,L] 

随着代码上面,你将能够访问/file.php作为/文件

删除HTML扩展

RewriteEngine on 


RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule^%{REQUEST_FILENAME}.html [NC,L] 

注:指令“上RewriteEngine叙述”应为每htaccess的顶部使用一次,所以如果你想要这条规则合并只是删除从第二条规则就行了。您也可以删除您选择的任何其他扩展名,只需将代码中的.php替换为它们即可。

快乐htaccessing!

相关问题