T Carter
T Carter

Reputation: 41

How to write expression to grab all after an expression and then rewrite in htaccess

I'm new to the rewriting of urls and regex in general. I'm trying to rewrite a URL to make it a 'pretty url' The original URL was

/localhost/house/category.php?cat=lounge&page=1

I want the new url to look like this:

/localhost/house/category?lounge&page=1

(like I say, I'm new so not trying to take it too far at the moment)

the closest I've managed to get it to is this:

RewriteRule ^category/(.*)$ ./category.php?cat=$1 [NC,L]

but that copies the whole URL and creates:

/localhost/house/category/house/category/lounge&page=1

I'm sure, there must be an easy way to say copy all after that expression, but I haven't managed to get there yet.

Upvotes: 2

Views: 234

Answers (2)

T Carter
T Carter

Reputation: 41

Thanks for all your suggestions, I took it back to this

RewriteRule category/([^/])/([0-9])/?$ category.php?cat=$1&page=$2 [NC,L]

which has done the trick, and I'll leave it at this for now.

Upvotes: 1

TheWandererLee
TheWandererLee

Reputation: 1032

I will try to help you:

  1. You probably have already, but try a mod rewrite generator and htaccess tester.
  2. From this answer: The query (everything after the ?) is not part of the URL path and cannot be passed through or processed by RewriteRule directive without using [QSA].
  3. I propose using RewriteCond and using %1 instead of $1 for query string matches as opposed to doing it all in RewriteRule.

For your solution, try:

RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^house/category$ house/category.php?cat=%1 [NC,L]

This will insert the .php and cat= while retaining the &page=


Anticipating your next step, the below mod rewrite may help get started in converting

http://localhost/house/category/lounge/1

to

http://localhost/house/category.php?cat=lounge&page=1

Only RewriteRule necessary here, no query string:

RewriteRule ^house/category/([^/]*)/([0-9]*)/?$ house/category.php?cat=$1&page=$2 [NC,L]

Use regex101 for more help and detailed description on what these regexes do.


If it still not working, continue to make the regex more lenient until it matches correctly:

Try to remove the ^ in RewriteRule so it becomes

RewriteRule category$ category.php?cat=%1 [NC,L]

Then it will match that page at any directory level. Then add back in house/ and add /? wherever an optional leading/trailing slash may cause a problem, etc.

Upvotes: 1

Related Questions