URL RewriteRule in .htaccess for index.php query p

2019-02-25 05:27发布

问题:

Example URL's:-

  • www.domain.com/index.php?bob
  • www.domain.com/index.php?jane
  • www.domain.com/index.php?fred

Need rewriting like:-

  • www.domain.com/bob
  • www.domain.com/jane
  • www.domain.com/fred

Have tried with many variations now but the closest I can get to is:-

  • www.domain.com/?bob
  • www.domain.com/?jane
  • www.domain.com/?fred

The below in .htaccess achieves this...

RewriteRule ^(.*)$ index.php?$1 [L,QSA]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]

Please could someone point out what I need to modify to bin the ? (question mark) in the URL?

Edit

Just noticed that since applying the answer given by anubhava below that robots.txt for example doesn't resolve to the .txt file but just displays the homepage.

.htaccess below:-

RewriteEngine On

RewriteBase /
RewriteCond %{THE_REQUEST} \s/+index\.php\?([^\s&]+) [NC]
RewriteRule ^ %1? [R=301,L]

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#pos1
RewriteRule ^([^/]+)/?$ index.php?$1 [L,QSA] <--

RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

#pos2

If I add the <-- line in pos1, the robots.txt URL returns a 404 page not found error.

If I add the <-- line in pos2, the robots.txt URL just displays the homepage.

Edit2

In the meantime, I have excluded robots.txt from rewrites by adding the following under Rewrite Base /:-

RewriteRule ^robots.txt - [L]

回答1:

You can use this code:

RewriteEngine On

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

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


回答2:

You can also use this:

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 

RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]