Nginx Redirect www to Non-www Config
A permanent redirect from www.example.com to example.com on HTTP and HTTPS. Enter your domain below for a ready server block.
- Free
- No Sign-Up
- Runs in Your Browser
Site Type
NoteThe certificate must cover www as well; the commands below request both names.
Server Block
# /etc/nginx/sites-available/example.com, generated at frabs.net/tools/nginx-config-generator/
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# add_header Strict-Transport-Security "max-age=31536000" always; # once HTTPS works everywhere
return 301 https://example.com$request_uri;
}
Install It
sudo certbot certonly --nginx -d example.com -d www.example.com # get the certificate first sudo nano /etc/nginx/sites-available/example.com # paste the config sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t && sudo systemctl reload nginx
Nginx Config Generator
Configuration
TypeRedirect www to Non-www
HTTPSLet's Encrypt with an HTTP redirect
Test Before Reloadnginx -t
A permanent redirect from www.example.com to example.com on HTTP and HTTPS.
Always run nginx -t before reloading: a bad file then leaves the old configuration serving instead of taking every site down.
Configurations
Reverse ProxyNode.js AppWebSocket ProxyStatic SitePHP-FPM (WordPress, Laravel)Redirect www to Non-www
Questions
How do I set up an Nginx redirect www to non-www?
Save the generated server block in /etc/nginx/sites-available/, link it into sites-enabled, run nginx -t and reload.
Free Tools
More tools
Nginx Config GeneratorServer blocks for reverse proxies, static sites and PHP, with HTTPS.Docker Compose GeneratorStarter compose.yaml files for common stacks, with safe defaults.SSL Certificate CheckerExpiry, issuer, chain, names and TLS version for any HTTPS site.Firewall Rule GeneratorGenerate iptables, nftables and UFW rules for common server set-ups.
Run VMs for other people?
Frabs stops spam, scans and floods leaving your customers' VMs, before the abuse report lands.