We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Reditect www to non-www

Hi guys!

Who i can redirect all urls with WWW to Non-WWW ?

example:

www.site.com/page → site.com/page
www.site.com → site.com
www.site.com/cat/subcat/title?id=123 → site.com/cat/subcat/title?id=123


85.5k

if you are running on apache

https://www.digitalocean.com/community/questions/can-you-use-virtual-host-config-conf-to-redirect-www-domain-to-non-www

https://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

I see it. But not understand how merge it with phalcon lines:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>


85.5k

if you try


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteBase / - try first without tihs, and then with it
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>


85.5k
Accepted
answer
edited Mar '16

RewriteEngine On - use the rewrite engine

RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f - if the request is a phisical file just return it

RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC] - match bla bla no idea really

then redirect to params from match


[QSA] - Query String Append.
[R] - redirect + code
[L] - last ( it will be the last rule that will be triggered )
[NC] - stands for that chain of events will be triggered as far as i know

but I suck at those so dont quote me :D

Thanks Izo, im trying and writing for results few time ago.

(sorry for my dialect)

This is solution for phalconphp framework, not for web service

    $request = $di->getRequest();

    if (strpos($request->getServerName(), 'www.') !== false) {
        $di->getResponse()->redirect($request->getScheme().'://'.substr($request->getServerName(), 4).$request->getURI());
    }

These lines should be included in public/index.php just before $app->handle()

Application (PhalconPHP) should not bother with this. Web server is in a perfect position to handle it. Folks, you need to follow the basics - let job to be done by a perfect candidate. Web server should handle this part as it interacts with user directly.