简体   繁体   中英

using htaccess to remove .php from URL

MY URL: http://localhost/test.php

I am using:

.htaccess:

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

PHP:

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

But all I get for $url is: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. Probably not desirable when doing url rewriting.

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.

#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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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