Issue with Redirecting from www to non-www in .htaccess

Hi,

I’m having an issue with redirects from www to non-www on my CMS Grav installation, which is a multilingual site. My configuration in the .htaccess file looks like this:

# Redirect www to non-www
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=303,L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=303,L]

The problem is that every redirect from www to the non-www version, when there is /something after the main address, causes a redirect to index.php, which results in a 404 error.

Examples:

I’ve noticed that if I comment out these lines that redirect from www to non-www, everything works fine, but then the site is accessible with both www and without www.

In the developer tools, I can see that the redirect is happening with a 303 status code. I used a 303 code to identify whether the redirect was coming from the .htaccess file or from CMS Grav.

The site is multilingual, which might affect how Grav processes these redirects. I’ve tried various settings in .htaccess, but the issue persists. Has anyone encountered a similar problem or knows how to resolve it? Could this be a conflict with Grav’s default redirects?

Any suggestions would be appreciated.

1 Like

From my experience with several multi-lingual Grav installations, this is not a problem with Grav.
As a non expert, I have had lots of luck with .htaccess Redirect Generator - Daniel Morell. Give it a shot or two.
I also remember that such directives, within your .htaccess, must be located at the top, before Grav’s own directives.

You may test with https://htaccess.madewithlove.com/.

2 Likes

Thank you for your response and the suggestions! I also found this topic: Redirects from www pages to index.php and I have the impression that moving the redirect code to the beginning of the .htaccess file has also helped in my case.

Thanks again for pointing me in the right direction!

I faced a similar situation. The solution was easy. I asked a question about the gpt bot redirect and he gave me a ready-made code that I just had to insert and enjoy.

in my case it was:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

1 Like

Great, I’m glad that worked for you! However, I’ve encountered situations where some systems override or modify the .htaccess file, so based on my experience, I always add my entries at the end of the file. Be cautious, because if you place the GPT-generated code below the default .htaccess code provided by the Grav CMS, it can lead to the issues mentioned. It’s something to keep in mind to avoid any unnecessary complications.

1 Like