Search code examples
wordpressapache.htaccessmod-rewrite

rewrite htaccess to remove slug product


I have some URLs like this:

https://example.com/product-name

I'll like to have .htaccess convert to SEO URLs in this way:

https://example.com/product/product-name

or otherwise.

This is how my .htaccess currently looks (it is placed in my root directory):

RewriteEngine On
RewriteRule ^([^/]+)$ product/$1 [L]

I've read and tried a lot of similar examples during the last 24 hours to no avail. I'm sure my server allows rewriting. Hope someone can help.


Solution

  • Maybe try something like the following at the top of your .htaccess file, before the existing WordPress directives. ie. Before the # BEGIN WordPress comment marker.

    RewriteRule ^([\w-]+)$ /product/$1 [R=302,L]
    

    This is a "redirect", not a "rewrite". Since you said this was for SEO.

    Ultimately, this may need to be a 301 (permanent) redirect, but test thoroughly first with a 302 (temporary) redirect to avoid potential cching issues.

    The regex ^([\w-]+)$ is also more restrictive than in your example. Specifically, it excludes dots, so won't match actual files like index.php, but will still match product-name.