---
title: "Nginx: Force HTTPS Redirect and Add www"
url: https://www.geekcorelab.cn/en-US/post/nginxs-mandatory-redirect-to-https-and-add-to-www
updated: 2026-11-04T03:39:21.908076Z
author: "hhjmk"
summary: "文章介绍了如何通过修改Nginx配置文件实现网站强制跳转HTTPS和添加WWW域名，包括使用rewrite方法强制HTTP到HTTPS的跳转和利用301重定向将非WWW域名跳转到带WWW的HTTPS域名，并提供了具体的配置代码和修改步骤，强调修改后需重启Nginx Server使设置生效。"
---

# Nginx: Force HTTPS Redirect and Add www

Redirect to HTTPS
-------

Although many websites support `https`, when you directly enter the URL in the browser address bar, they are accessed via the `http` protocol by default, hence the need to force `http` to redirect to `https` arises  
**Use the rewrite method to force HTTPS**

```
if ($server_port !~ 443){
    rewrite ^(/.*)$ https://$host$1 permanent;
}

```

**Modification method**  
Enter the virtual host configuration file directory  
![Enter the configuration file directory](/uploads/import-placeholder/40)
  
View the virtual host to modify  
![View the virtual host to modify](/uploads/import-placeholder/226)
  
Use the vim editor to modify the configuration file and add the above code  
![Just add the code](/uploads/import-placeholder/302)
  
After modification, you need to restart Nginx Server for it to take effect.

Redirect to WWW
-----

For some websites, the main domain has `www` added, but you can still access `gqink.cn` if you want to access it; then add the following code to redirect to `www.biliwind.com`  
**Use a 301 redirect to HTTPS and add www**

```
if ($host ~ '^gqink.cn'){
    return 301 https://www.biliwind.com$request_uri;
}

```

**Modification method**  
Enter the virtual host configuration file directory  
![Enter the configuration file directory](/uploads/import-placeholder/40)
  
View the virtual host to modify  
![View the virtual host to modify](/uploads/import-placeholder/226)
  
Use the vim editor to modify the configuration file and add the above code  
![Just add the code](/uploads/import-placeholder/143)

After modification, you also need to restart Nginx Server for it to take effect.  
This article uses the lnmpa environment for demonstration.
