RikuAnsem001
RikuAnsem001

Reputation: 1

mod_rewrite rewrites to directory twice?

My index page and links like /page work fine, however my rewrite rule to remove the php from the /page.php seems to be writing the url incorrectly.

Example: http://www.example.com/folder/page.php will redirect to http://www.example.com/folder/folder/page which does not exist

# Remove .php extention
RewriteCond %{THE_REQUEST} \s/(.+?)\.php(?:\s|\?) [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %1? [R=301]

# Rewrite to PHP file extension (if existing) without changing url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L]

Upvotes: 0

Views: 504

Answers (2)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Your problem is that you put the above code in .htaccess file in this directory http://www.example.com/folder/ so when a page comes without .php it will be handled fine for example if you request http://www.example.com/folder/page it will give you this result http://www.example.com/folder/page , without .php because it will be handled by the second section of your given code

# Rewrite to PHP file extension (if existing) without changing url RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.+)$ $1.php [L]

it means when file comes without .php will result the same file , good.

but the problem when you write the same request along with .php so the request will be http://www.example.com/folder/page.php and this according to section one of your code

# Remove .php extention RewriteCond %{THE_REQUEST} \s/(.+?)\.php(?:\s|\?) [NC] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ %1? [R=301]

will immediately remove the extension .php correctly but the problem is in line of code:

 RewriteRule ^ %1? [R=301]

The path in a RewriteRule target is incorrect so you see it twice and you should add

RewriteBase /

line above

RewriteRule ^ %1? [R=301]

or just replace it with :

RewriteRule ^ /%1? [R=301]

and it will work fine . `

Upvotes: 1

anubhava
anubhava

Reputation: 785216

You can use these rules:

# remove .php extension
RewriteCond %{THE_REQUEST} ^GET\s(.+?)\.php[\s?/] [NC]
RewriteRule ^ %1? [R=301,L]

# Rewrite to PHP file extension (if existing) without changing url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]

Make sure to clear your browser cache before testing this.

Upvotes: 0

Related Questions