简体   繁体   中英

Force www to https in Express NodeJS

I build a NodeJS app with express and in Firefox when I type domain name.com it's not redirecting to https://www.<domain_name>.com

Can someone help on how to redirect <domain_name>.com and www.<domain_name>.com with https?

  let host = req.headers.host;
  if (!host.match(/^www\..*/i)) {
    return res.redirect(301, "https://www." + host + req.url);
  }
  next();
}

I tried the above one but no luck on Firefox.

You have to edit your http server configuration accordingly:

apache: etc/apache2/sites-available/000-default

change to this:

RewriteEngine on
  RewriteCond %{HTTPS} !=on
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

or

nginx: etc/nginx/sites-available/default

change to this:

server {
      listen 80;
      server_name your_domain.com www.your_domain.com;
      return 301 https://$host$request_uri;
}

If you still experience issues, edit .htaccess file:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?supergenscript\.com
RewriteRule ^(.*)$ https://www.supergenscript.com/$1 [R=301, L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM