HTAcces Rewrite Directory Format to Query String

Viewed 46

I am really struggling to understand how I can use htaccess / rewrite to change a url in the form www.domain.com/home/ to www.domain.com/index.php?route=home. I thought I cracked it, but the url shown in the browser also changed to show the query string. I wanted the displayed url to change along with rewrite.

I also wanted to redirect http to https. I see other websites achieve this (stackoverflow for example).

My current attempt is:

RewriteRule ^/?(\w*?)/?$ https://www.%{HTTP_HOST}/index.php?route=$1 [R=301,NC,L]
2 Answers

Could you please try following. Written as per your samples. Also please clear your browser cache after placing these Rules into your .htaccess file. You are using R=301 redirection which is why it changes the url to url of backend in browser itself, you don't need it.

RewriteEngine ON
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NE,L]

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ index.php?route=$1 [L]

When you have http:// or https:// in target Apache will always send a R=302 flag to clients, forcing a full redirect.

Here, you actually need 2 separate rules:

  1. http -> https
  2. Rewrite rule to index.php for non-files and non-directories

Suggested .htaccess:

RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(\w+)/?$ index.php?route=$1 [QSA,L]

Make sure to clear your browser cache before you test these rules.

Related