0

I have a .htaccess file that is redirecting URLS like this:

RewriteRule    ^companies/([0-9]{1,20})/(.*)/?$    /php/company-profile.php?id=$1    [NC,L]

Which matches a URL 'companies/12345/company-name-safe' and grabbing the unique id for company-profile.php.

This works great. But I include a list of jobs by that company on the page, which has pagination & order_by functionality.

So I also need to capture any extra URL params and pass to the php file.

E.g for a url: companies/12345/company-name?page=2&order_by=date+DESC

I don't want to have to change my URL structure if possible, I always want page 1 to be a clean URL without '?id=12345' on the end.

How can I do this?

rpsep2
  • 3,061
  • 10
  • 39
  • 52
  • You only have to add `QSA` flag to your rule (after `L` for instance). This way, the query string will be appended. From your example `companies/12345/company-name?page=2&order_by=date+DESC` will be rewritten to `/php-profile.php?id=12345&page=2&order_by=date+DESC` – Justin Iurman Jan 16 '16 at 23:35
  • 1
    @JustinIurman this worked, thank you! Will accept as the official answer if you wanted to write again as an answer – rpsep2 Jan 16 '16 at 23:40
  • Possible duplicate of [How can I mod\_rewrite and keep query strings?](http://stackoverflow.com/questions/12873137/how-can-i-mod-rewrite-and-keep-query-strings) – Anonymous Jan 17 '16 at 02:20

1 Answers1

3

You only have to add a QSA flag to your rule

RewriteRule ^companies/([0-9]{1,20})/(.*)/?$ /php/company-profile.php?id=$1 [NC,L,QSA]

This way, the query string will be appended. From your example companies/12345/company-name?page=2&order_by=date+DESC will be rewritten to /php-profile.php?id=12345&page=2&order_by=date+DESC.

The solution above is only valid if query string parameters can have the same names in your rule. Otherwise, you can capture them separately with a RewriteCond on %{QUERY_STRING} and then append them manually in the rule, for instance:

RewriteCond %{QUERY_STRING} ^page=([^&]+)&order_by=([^&]+)$ [NC]
RewriteRule ^companies/([0-9]{1,20})/(.*)/?$ /php/company-profile.php?id=$1&xxx_page=%1&xxx_order_by=%2 [NC,L]  

Note that in this current case, you don't need QSA flag anymore

Justin Iurman
  • 18,954
  • 3
  • 35
  • 54