Dave
Dave

Reputation: 433

regex in my RewriteRule is OK, but .htaccess does not work

I'm having a lot of trouble getting my .htaccess ReWrite to work on my apache web server. I've read several tutorials and tested my regex matching with Grep.

Here is the code:

    RewriteRule \?action=viewArticle&articleId=([0-9]*)&categoryId=([0-9])$ essays/$1 [R=301,L]

here is a url I'm trying to match:

http://mysite.com/?action=viewArticle&articleId=15&categoryId=1

and change to

http://mysite.com/essays/15

UPDATE: Solution! with a very excellent tutorial from Jon. It was very important that I put <base href="/"> in my header file to get the css to work correctly.

Final rewrite looked like this:

RewriteCond %{THE_REQUEST} /?action=viewArticle&articleId=([0-9]*)&categoryId=([0-9])
RewriteRule ^$ /essays/%1? [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^essays/([0-9]+) /?action=viewArticle&articleId=$1&categoryId=([0-9]) [L]

Upvotes: 0

Views: 164

Answers (1)

Jon Lin
Jon Lin

Reputation: 143856

You can't match hosts or query strings inside a RewriteRule, you need to match against the %{HTTP_HOST} and %{QUERY_STRING} variables in a RewriteCond directive:

RewriteCond %{HTTP_HOST} mysite\.com$ [NC]
RewriteCond %{QUERY_STRING} ^action=viewArticle&articleId=([0-9]*)&categoryId=([0-9])$
RewriteRule ^$ /essays/%1? [L,R=301]

This redirects the browser (changing the URL in the address bar) when someone goes to http://mysite.com/?action=viewArticle&articleId=15&categoryId=1 to http://mysite.com/essays/15

You don't need the %{HTTP_HOST} condition if your htaccess file only serves a single host.

Upvotes: 2

Related Questions