Search code examples
phpregex.htaccess

RewriteRule Not Working in .htaccess file


I'm trying to change the URL of my website to show only the ID but It seems to not work...

I don't know why.. other commands of RewriteRule work well.. Actually the .htaccess file looks like belove

RewriteEngine On

RewriteRule ^/?([0-9a-zA-Z-]+)/$ article.php?articleId=$1 [L]

I want that it works like this: Old_URL(to modify): mywebsite.it/article.php?articleId=15
I want something like this:mywebsite.it/article/15
But the URL remains the same actually: always display this:
mywebsite.it/article.php?articleId=15
Thanks in advance to every help :)


Solution

  • An internal rewrite will never change the URL visible in the browser. You are probably looking for an external redirection. Or better the combination of both:

    RewriteEngine On
    # externally redirect old URL
    RewriteCond %{QUERY_STRING} (?:^|&)articleId=(\d+)(?:&|$)
    RewriteRule ^/?article/?$ /article/%1 [R=301,L]
    # internally rewrite new URL
    RewriteRule ^/?article/(\d+)/?$ /article.php?articleId=$1 [END]
    

    Those rules are meant to be implemented on top level. Best in the actual http server's host configuration. If you do not have access to that then a distributed configuration file will work (".htaccess") when located in the host's DOCUMENT_ROOT, but support for that needs to be enabled.

    It is a good idea to start out using a R=302 temporary redirection and only change that to a R=301 permanent redirection once you are happy with how things work. That prevents caching issues on the client side.