Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WWW to non-WWW Redirect with PHP

Tags:

I want to redirect all www.domain.com requests to domain.com with PHP, basically:

if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.') {     header('Location: http://' . substr($_SERVER['SERVER_NAME'], 4)); exit(); } 

However I do want to maintain the requested URL like in SO, for e.g.:

http://www.stackoverflow.com/questions/tagged/php?foo=bar 

Should redirect to:

http://stackoverflow.com/questions/tagged/php?foo=bar 

I don't want to rely on .htaccess solutions, and I'm unsure which $_SERVER vars I'd have to use to make this happen. Also, preserving the HTTPS protocol would be a plus.

How should I do this?

like image 807
Alix Axel Avatar asked Jan 17 '10 00:01

Alix Axel


People also ask

Why does PHP not redirect to another page?

In short, the PHP header not redirecting error occurs mainly due to the absence of ob_start() function, incorrect header formats, and so on.


1 Answers

Try this:

if (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {     header('Location: http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 's':'').'://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);     exit; } 
like image 165
Gumbo Avatar answered Sep 18 '22 18:09

Gumbo