I have some trouble to route my web site to same redirect but with www server side. For example if a user browses my web site example.com , i should redirect it to www.example.com. I found nextjs redirect and did something like in next.config.js as follow.
module.exports = {
async redirects() {
return [
{
source: '/',
destination: 'https://www.example.com/',
statusCode: 301
},
]
},
}
but when i publish this code, i got too many redirect error as a normally but i cant found a solution to put a condition if the source path does not start with www then start this redirect rules. Anyone helps me how to do this ? I dont need client side redirects.
I don't think nextjs provides such an opportunity because it targets the base url that comes after your domain name. In my opinion, the best way to achieve this is to use a .htaccess
file. You can just pass this code into it.
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Also if you want to redirect from http to https add this code below
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^(.*)$ http%1://www.%{HTTP_HOST}/$1 [R=301,L]