skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search