salmanpervaiz
salmanpervaiz

Reputation: 23

.htaccess rewrite rule causes endless loop

I want my .htaccess file to redirect to some page if any wildcard as a subdomain entry hit the browser. i.e. I want

sam.xyz.com

To redirect to

sam.xyz.com/view.php?id=sam

I am using following rewrite rules for redirect.

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.xyz.com [NC]

RewriteCond %{HTTP_HOST} ^([^.]+).xyz.com

RewriteRule ^(.*)$ /view.php?id=%1 [L,R]

Problem i am facing is that it does not shift to new domain keeping query string instead it generates an endless loop

sam.xyz.com

redirects to

http://sam.xyz.com/view.php?id=sam

But doesnt move to url above without endless loop. Kindly help me out. Thanks in advance,

Upvotes: 2

Views: 4310

Answers (2)

NeilB
NeilB

Reputation: 41

You are redirecting to: prefix.domain.tld/view.php?id=prefix

Ensure that the url does not contain: id=prefix.

This solution prevents, that someone call's the url: aaa.example.com/view.php?id=bbb

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.xyz.com [NC]
RewriteCond %{HTTP_HOST} ^([^.]+).xyz.com
RewriteCond %1::%{QUERY_STRING} !^([^:]+)::.*id=\1
RewriteRule ^ /view.php?id=%1 [L,R]

Note: (.*) in the rewrite rule is obsolete.

Leave the R away to do not redirect the visitor to the url (/view.php?id=%1)

Upvotes: 1

Amine Hajyoussef
Amine Hajyoussef

Reputation: 4420

you should add a condition for redirect to prevent redirection loop:

RewriteCond %{REQUEST_URI} !^/view\.php

the whole code would be:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.xyz.com [NC]
RewriteCond %{HTTP_HOST} ^([^.]+).xyz.com
RewriteCond %{REQUEST_URI} !^/view\.php
RewriteRule ^(.*)$ /view.php?id=%1 [L,R]

Upvotes: 3

Related Questions