Zsolt Janes
Zsolt Janes

Reputation: 840

Redirect with htaccess with variable

I would like to redirect all my php files to without php extension. Like news.php to news or articles.php to articles. I know about this htacces command:

Redirect 301 /news.php /news

But I would like to make with variable, something like this but does not work:

Redirect 301 ^(.*)$ /$1.php

Upvotes: 0

Views: 55

Answers (2)

anubhava
anubhava

Reputation: 785128

You will need a redirect rule to remove .php extension and a rewrite rule to add .php extension silently. Try these 2 rules in your root .htaccess:

RewriteEngine On

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

# To internally redirect /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Upvotes: 0

arkascha
arkascha

Reputation: 42915

You can use the rewrite module for this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule 301 ^(.*)\.php$ $1 [L,QSA]

Upvotes: 1

Related Questions