如何使URL显示不带www的主机名?含示例及代码需求
Hey there! Let's walk through how to get your URLs showing without that pesky www prefix—using your example of turning https://www.google.com/search/ into just google.com for display, plus covering both server configs and code implementations you might need.
First, you'll want to make sure any traffic to the www version of your site automatically redirects to the non-www one. This ensures users always land on the clean URL, and search engines will prioritize the non-www version in their indexes.
Nginx Configuration
If you're using Nginx, edit your server block config (usually in /etc/nginx/sites-available/ or similar) to add these redirect rules:
# Handle HTTP traffic for www server { listen 80; listen [::]:80; server_name www.yourdomain.com; return 301 $scheme://yourdomain.com$request_uri; } # Handle HTTPS traffic for www server { listen 443 ssl; listen [::]:443 ssl; server_name www.yourdomain.com; return 301 $scheme://yourdomain.com$request_uri; # Don't forget to include your SSL certificate paths here ssl_certificate /path/to/your/certificate.pem; ssl_certificate_key /path/to/your/private-key.pem; }
After making changes, run sudo nginx -t to test the config, then sudo systemctl reload nginx to apply it.
Apache Configuration
For Apache, you can add these rules to your .htaccess file (or virtual host config):
RewriteEngine On # Redirect www to non-www with permanent 301 redirect RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
The [NC] flag makes the match case-insensitive, and [R=301,L] marks this as a permanent redirect and stops processing further rules.
If you need to parse a URL and display just the non-www hostname (like showing google.com instead of www.google.com to users), here are examples for common languages:
JavaScript (Browser/Node.js)
function getCleanHostname(url) { const urlObj = new URL(url); let hostname = urlObj.hostname; // Strip leading www. if it exists if (hostname.startsWith('www.')) { hostname = hostname.slice(4); } return hostname; } // Test it out const originalUrl = 'https://www.google.com/search/'; console.log(getCleanHostname(originalUrl)); // Output: "google.com"
Python
from urllib.parse import urlparse def get_clean_hostname(url): parsed_url = urlparse(url) hostname = parsed_url.hostname if hostname and hostname.startswith('www.'): return hostname[4:] return hostname # Example usage original_url = 'https://www.google.com/search/' print(get_clean_hostname(original_url)) # Output: "google.com"
PHP
function getCleanHostname($url) { $parsedUrl = parse_url($url); if (!isset($parsedUrl['host'])) return ''; $hostname = $parsedUrl['host']; if (str_starts_with($hostname, 'www.')) { return substr($hostname, 4); } return $hostname; } // Test the function $originalUrl = 'https://www.google.com/search/'; echo getCleanHostname($originalUrl); // Output: "google.com"
Note: For PHP versions before 8.0, replace str_starts_with with substr($hostname, 0, 4) === 'www.'.
- Double-check your DNS records: Make sure both
yourdomain.comandwww.yourdomain.compoint to your server's IP (otherwise the redirect won't work). - Use 301 redirects: Permanent redirects tell search engines to transfer ranking weight from the www to non-www version, avoiding duplicate content issues.
- CDN users: If you're using a CDN like Cloudflare, you can configure the www-to-non-www redirect directly in the CDN dashboard instead of on your server.
内容的提问来源于stack exchange,提问作者user9300109

