Query string rewriting using .htaccess

2019-03-02 17:44发布

问题:

i am trying to rewrite a URL for SEO purpose.

The old URL is:

http://www.domain.net/index.php?p=beer

The new URL should be:

http://www.domain.net/beer

My Code in the .htaccess is:

RewriteRule ^([^/\.]+)/?$ index.php?p=$1

Even after hours of research, i have no clue why this is not working :(

Here is the complete .htaccess:

RewriteEngine on 
RewriteCond %{HTTP_USER_AGENT} Teoma
RewriteRule ^.* - [F]
rewritecond %{HTTP_HOST} !^www\.domain\.net$ [NC]
rewriterule ^(.*)$ http://www\.domain\.net/$1 [R=301,L]

RewriteCond %{QUERY_STRING} ^p=uppic$
RewriteRule ^index\.php$ /? [L,R=301]

RewriteRule ^([^/\.]+)/?$ index.php?p=$1

# Pwd service

AuthType Basic
AuthName "Service"
AuthUserFile /xxxx/www/xxxxxx/xxxxx/xxxxxx/.htpasswd


<Files admin.php>
Require user xxxxxxx
</Files>

Options -Indexes

Thanks in advance!


My final question to this code is:

RewriteRule ^([^/\.]+)/?$ index.php?p=$1

Makes working :

http://www.domain.net/beer

and beer is refering to that page:

http://www.domain.net/index.php?p=beer

Which is great! But if i put a / behind beer, e.g.:

http://www.domain.net/beer/

my beer.php file runs at another path, so no css, images, js and so on is included. Any ideas how to fix that without changing the html to http://www.domain.net/style.css ...?

回答1:

If you want to capture part of the query string, you must use a RewriteCond with QUERY_STRING

RewriteEngine On
RewriteCond %{QUERY_STRING} p=(.+)
RewriteRule ^/?index.php$ /%1? [R,L]

This redirects the client to the new URL http://www.domain.net/beer.



回答2:

Have you tried this:?

^([^/\.]+)\/?$

Otherwise I would try the .htacces without the other stuff.

Just:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/\.]+)\/?$ index.php?p=$1