简体   繁体   English

使用htaccess从URL中删除.php

[英]using htaccess to remove .php from URL

MY URL: http://localhost/test.php 我的网址: http://localhost/test.php

I am using: 我在用:

.htaccess: 的.htaccess:

RewriteEngine On 
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

PHP: PHP:

$url = $_GET['url'];
echo var_dump($url);

But all I get for $url is:NULL NULL NULL NULL NULL NULL 但我得到的$ url是:NULL NULL NULL NULL NULL NULL

Edit: adjusted to handle both the redirect and the rewrite. 编辑:调整为处理重定向和重写。

RewriteEngine On 
RewriteBase /

# Redirect .php URLs to rewritten URLs
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.+)\.php$ $1 [L,QSA,R=301]

# Rewrite URLs for processing by router (index.php)
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L,NC]

You should exclude the RewriteCond %{REQUEST_FILENAME} !-d condition, as it will attempt to access a directory if your URL matches it. 您应该排除RewriteCond %{REQUEST_FILENAME} !-d条件,因为如果您的URL匹配,它将尝试访问目录。 Probably not desirable when doing url rewriting. 在进行网址重写时可能不太理想。

index.php 的index.php

$url = isset($_GET['url']) ? $_GET['url'] : null;
var_dump($url);

I just wanted to leave this somewhere for future users. 我只是想把这个留给未来的用户。 This removes both HTML and PHP extensions from URLS. 这将从URLS中删除HTML和PHP扩展。

#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

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

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM