I am new to the URL Rewriting using .htaccess and I am strugguling with it.
What I want is to change the url similar to this http://www.example.org/index.php?page=contact&lang=en (lang has 3 options while the page value is changing depending on the current page) for example - to https://example.org/en/contact - non-www and https version).
Also if someone visits https://example.org/ I want to redirect them to https://example.org/en (default)
So far this is what I have in .htaccess and it doesn't work propertly.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0&lang=$1 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)(&lang=en)?$
RewriteRule ^index\.php$ /%1? [R=301,L]
Here is a .htaccess
that matches your needs
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteRule (.*) https://%{HTTP_HOST}/en?
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteCond %{QUERY_STRING} page=(\w+)&lang=(\w+)
RewriteRule (.*) https://%{HTTP_HOST}/%1/%2?
Explanation
The first condition and rule
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteRule (.*) https://%{HTTP_HOST}/en?
will redirect the following urls to http://www.example.org/en
http://www.example.org
http://www.example.org/
http://www.example.org/index.php
The second conditions and rule
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteCond %{QUERY_STRING} page=(\w+)&lang=(\w+)
RewriteRule (.*) https://%{HTTP_HOST}/%1/%2?
will redirect the following urls to http://www.example.org/contact/en `
http://www.example.org/index.php?page=contact&lang=en
http://www.example.org/?page=contact&lang=en
http://www.example.org?page=contact&lang=en
change contact
and en
with other values to see the changes
Here is a Live example
RewriteEngine On
#1
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
#2
RewriteRule ^/?$ https://%{HTTP_HOST}/en? [R=301,L]
#3
RewriteCond %{REQUEST_URI} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)&lang=(\w+)$
RewriteRule "(.*)" "https://%{HTTP_HOST}/%2/%1?" [R=301,L]
Handles all Requests without https or with www.
http://www.example.org/whatever => https://example.org/whatever
Handles root /
requests and add en
as default language
https://example.org/ => https://example.org/en
Handles the index.php?page=x&lang=x Requests and replace Query Params with Path segments
https://example.org/index.php?page=contact&lang=en => https://example.org/en/contact
All 3 together should fulfill your described requirements
http://www.example.org/index.php?page=contact&lang=en => https://example.org/en/contact
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.