如何用Nginx将域名重定向至带www的HTTPS?配置遇阻求助
Let’s break down how to fix your domain access issues step by step—this is a super common snag with Nginx server blocks, so we’ll get you sorted in no time.
Head over to your Nginx sites-available directory (usually /etc/nginx/sites-available/) and check the configuration files for your domains. You likely need two properly structured server blocks to handle both the bare domain (yoalfaaz.com) and the www subdomain.
Fix the HTTP Bare Domain Redirect
If you don’t have a server block for yoalfaaz.com, create one (or add it to your existing config) to redirect traffic to the www version (or vice versa, if you prefer the bare domain as primary):
server { listen 80; server_name yoalfaaz.com; # Point to your website files (match your www block's root) root /var/www/website-folder; index index.html index.htm index.nginx-debian.html; # Redirect permanently to www.yoalfaaz.com return 301 $scheme://www.yoalfaaz.com$request_uri; }
Verify the www Server Block
Ensure your existing www block is correctly set up to serve content:
server { listen 80; server_name www.yoalfaaz.com; root /var/www/website-folder; index index.html index.htm index.nginx-debian.html; location / { try_files $uri $uri/ =404; } }
Your https://yoalfaaz.com issue is almost certainly missing SSL certificates and HTTPS server blocks. We’ll use Certbot (for free Let’s Encrypt certificates) to automate this:
- Install Certbot and its Nginx plugin:
sudo apt update sudo apt install certbot python3-certbot-nginx
- Run Certbot to generate certificates and update your Nginx config automatically:
sudo certbot --nginx -d yoalfaaz.com -d www.yoalfaaz.com
Follow the prompts to choose your redirect preference (usually redirect all HTTP traffic to HTTPS) and complete the setup. Certbot will handle adding HTTPS server blocks and updating redirects for both domains.
Make sure your domain’s DNS is pointing correctly to your DigitalOcean droplet:
- Create an A record for
yoalfaaz.compointing to your server’s public IP - Create an A record for
www.yoalfaaz.compointing to the same IP
You can verify this with the dig command:
dig yoalfaaz.com A +short dig www.yoalfaaz.com A +short
Both should return your server’s IP address.
Always check for syntax errors before restarting Nginx:
sudo nginx -t
If you see nginx: configuration file /etc/nginx/nginx.conf test is successful, restart the service to apply changes:
sudo systemctl restart nginx
- Firewall Check: Ensure ports 80 (HTTP) and 443 (HTTPS) are open. Run
sudo ufw status—if "Nginx Full" isn’t allowed, add it withsudo ufw allow 'Nginx Full'. - Clear Browser Cache: Old redirects might be cached—test in incognito mode or clear your browser’s cache.
- Certbot Verification: Check if certificates were generated successfully by looking in
/etc/letsencrypt/live/yoalfaaz.com/—you should seefullchain.pemandprivkey.pemfiles.
内容的提问来源于stack exchange,提问作者Gurjyot Singh

