Skip to content
Advertisement

htaccess how to rewrite this url

How to rewrite this URL:

JavaScript

to:

JavaScript

also, how do I still preserve cat_id param?

I tried this but it does not work:

JavaScript

Advertisement

Answer

When I add this code and go to illustrations.php?category=cats it does not change the URL in the browserbar.

Yes, that is “correct”.

The code you posted internally rewrites the URL /category/cats (which is the URL you should be linking to in your HTML source) back to the actual filesystem/URL path: /illustrations.php?category=cats. This is required in order to make the “pretty” URL /category/cats “work”.

You can’t change the URL structure using .htaccess only – if that is what you are implying. You do need to actually change the physical URLs in your HTML source.

You could implement an external redirect (not a rewrite) from /illustrations.php?category=cats to the canonical URL /category/cats using .htaccess, but note that this is only to benefit SEO (and third parties that might have already linked to the old URLs). This is a necessary additional step if you are changing an existing URL structure and SEO is a concern, but it is not part of the “working” of your site.

how do I still preserve cat_id param

You would need to include the value of the cat_id parameter in the URL. eg. /category/cats/1 (as @arkascha suggested in comments) or /category/1/cats – depending on which value is more important. I would put the more important value first, since URLs can be accidentally cropped when shared.

JavaScript

This rule could be simplified. Filesystem checks are relatively expensive. It looks like you could remove both of these by making your regex more specific. eg. Could /category/1/cats ever map to a file? Do you need directories to be accessible? I would expect the answer to both those questions is “no”.

I would also decide on whether to allow trailing slashes or not, rather than allowing both (as in your current rule). Strictly speaking this creates duplicate content (two URLs; same content), so requires additional steps to resolve. Your example URL(s) do not contain a trailing slash.

So, you could simplify your rules to the following in order to rewrite /category/1/cats (no trailing slash) to /illustrations.php?category=cats&cat_id=1

JavaScript

This assumes cat_id can be 1 or more digits (0-9). And category is limited to the following characters: a-z, A-Z, 0-9, _ (underscore), - (hyphen).

With regex it is preferable to be as restrictive as possible. By omitting the dot (.) from the last path segment in the above rule it cannot match a physical file (assuming all your files have file extensions).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement