Rushi Adhia
Rushi Adhia

Reputation: 11

htaccess redirect + rewrite for same URLs

I have a URL mydomain.com/abc/xyz and I want to redirect it to mydomain.com/def

Now, I also want to rewrite mydomain.com/abc/xyz URL to mydomain.com/def that means if someone opens mydomain.com/def it should open the content of mydomain.com/abc/xyz

I have tried both the redirection and the rewriting and they both work individually, but not combined.

Here's the code

RewriteRule ^abc/xyz/ http://mydomain. com/def [L,R=301]
RewriteRule ^/def /abc/xyz  [NC,L]

In simple words lets consider URL1 = mydomain.com/abc/xyz and URL2 = mydomain.com/def

I want URL2 as pretty URL and should open content of URL1 But if someone opens URL1, I want them to be redirected to URL2 and show the content of URL1

So, first redirect and then show content using rewrite rule.

Upvotes: 0

Views: 51

Answers (1)

arkascha
arkascha

Reputation: 42925

I wonder if that rewriting rule really works separately... You say you are using a ".htaccess" file, so a distributed configuration file. When implementing rewriting rules in such location (as opposed to the central configuration of the http server) the matching pattern in rewrite rules is applied to a relative path. That actually makes a lot of sense if you think about it and it is clearly documented. That means that your matching pattern would never match ...

Here is a slightly modified version that works likewise, whether you implement those rules in a distributed or a central configuration file:

RewriteEngine on
RewriteRule ^/?abc/xyz/ https://example.com/def [L,R=301]
RewriteRule ^/?def /abc/xyz  [NC,L]

And most likely you also want to be a bit more precise:

RewriteEngine on
RewriteRule ^/?abc/xyz/?$ https://example.com/def [L,R=301]
RewriteRule ^/?def/?$ /abc/xyz  [NC,L]

Upvotes: 0

Related Questions