1

There are plenty of answers on removing index.php with mod_rewrite in .htaccess but I need to remove index.php? from incoming URLs and rewrite them all, i.e. /index.php?pagename.php to /pagename.php .

Either of these work separately, and they remove index.php

1)

RewriteBase /
RewriteRule ^index.php?/(.*)$ $1 [R=301,L]

2)

RewriteBase /
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

But not the ?, as the URLs look like this: example.com/?pagename.php

The issue is that the ? is a special character in regex, so if that's added, I understand that it needs to be escaped. But neither of these work:

1)

RewriteBase /
RewriteRule ^index.php\??/(.*)$ $1 [R=301,L]

2)

RewriteBase /
RewriteCond %{THE_REQUEST} ^GET.*index\.php\? [NC]
RewriteRule (.*?)index\.php\?/*(.*) /$1$2 [R=301,NE,L]

How do I correctly escape the ? in index.php? ?

This answer does not work for me; it leaves the ?: Mod_rewrite rule to remove index.php

And beyond that: are there appreciable differences between the two rewrite rules?

2
  • Why not example.com/?page=pagename.php then use the page variable?? Commented Jul 25, 2017 at 18:50
  • index.php?pagename.php are existing links; I can't change them. Commented Jul 25, 2017 at 19:56

1 Answer 1

1

You can use this rule in site root .htaccess:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+(?:index\.php)?\?([^&\s]+)\s [NC]
RewriteRule ^ /%1? [R=301,L]
Sign up to request clarification or add additional context in comments.

6 Comments

Nice! Works great. And these are 301 redirects as I see from R=301 ?
Of course, another issue :) It appears that most of the site is indexed by Google as /?PageName.php while also accessible and internally linked as /index.php?PageName.php . Your rule still works, but I tried RewriteCond %{THE_REQUEST} \s/+\?(\S+) [NC] as a second rule below your rule to remove the ?, but my rule appears to redirect all to index.php. Any ideas?
Thanks, I see what you did, but each still redirects to root. Does the second line RewriteRule . /%1? [R=301,L] also need to account for the ? by itself ?
I am trying example.com/?PageName.php Each attempt redirects to root but still shows the ?PageName.php in the browser bar.
Nice! Works great. Thanks! I'll edit my question to include the ? case.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.