Home Apache rewrite root to subdirectory and keeping the request_uri
Reply: 1

Apache rewrite root to subdirectory and keeping the request_uri

EagleTheDev
1#
EagleTheDev Published in 2018-01-10 15:05:06Z

I would like to rewrite a URL such as https://example.com/abcde to https://example.com/en/abcde and https://example.com/acefr to https://example.com/en/acefr.

I have tried something like this:

RewriteRule ^$ /en [R=301]

It can redirect me from https://example.com/ to https://example.com/en/; but it fails when my URL is https://example.com/abcde, keeping the original URL.

What should I write in the config file?

Many thanks!

UPDATE 1: I have probably missed to state that there are other subdirectories under the root and I still need to keep access, such as https://example.com/zh/ and https://example.com/hub/.

Lastly, I don't want to keep the URL unchanged. I need it to be changed as well. I don't mind to use 'RedirectMatch' rule.

For better understanding:

https://example.com/abcde  ==> https://example.com/en/abcde
https://example.com/zh/abcde  #KEEP!  (in which subdirectory "zh/" exists)
https://example.com/en/ffsd  #KEEP!  (in which subdirectory "en/" exists)
https://example.com/hub/iyukmyjnrtb  #KEEP! (in which subdirectory "hub/" exists)

Thanks a lot!

UPDATE 2: Sorry for any misunderstanding. I also need the redirection for the following:

https://example.com/abcde/edgs  ==> https://example.com/en/abcde/edgs (in which subdirectory "abcde/" does not exists)

Thanks!

anubhava
2#
anubhava Reply to 2018-01-10 18:49:12Z

You can use this rule in your site root .htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 ^$ [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteRule ^(?!en/)([^/]+/)?.*$ /en/$0 [R=301,L,NC]

Make sure to clear your browser cache before testing.

Here is an explanation of each line of this rule:

# if this request is not for an existing file
RewriteCond %{REQUEST_FILENAME} !-f

# if this request is not for an existing directory
RewriteCond %{REQUEST_FILENAME} !-d

# if $1 is empty
RewriteCond $1 ^$ [OR]

# if $1 is not an existing file
RewriteCond %{DOCUMENT_ROOT}/$1 !-d

# (?!en/) is a negative lookahead to assert we don't already have /en/ at start
# ([^/]+/)? captures an optional match before first / into $1
# $0 represents full match here that is between ^ and $
# /en/$0 prefixes /en/ before current Request URI
RewriteRule ^(?!en/)([^/]+/)?.*$ /en/$0 [R=301,L,NC]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.360672 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO