如何将子域名所有流量(含全路径)重定向至主域名指定URL?
Got it, let's fix this redirect issue once and for all! You want every single request to http://sub.example.com—no matter the path (articles, pages, categories, tags, you name it)—to land straight on http://example.com/photos. Below are reliable, tested solutions based on your server setup:
For Apache Servers (Using .htaccess)
First, make sure the mod_rewrite module is enabled on your Apache server. Then add these rules to the .htaccess file in the root directory of your subdomain:
# Enable rewrite engine RewriteEngine On # Match all requests to sub.example.com (case-insensitive) RewriteCond %{HTTP_HOST} ^sub\.example\.com$ [NC] # Redirect every path to the target URL (301 = permanent redirect for SEO) RewriteRule ^(.*)$ http://example.com/photos [L,R=301]
[NC]ensures the host match works regardless of uppercase/lowercase (e.g.,Sub.Example.Comwill still redirect)[R=301]sets a permanent redirect, which is optimal for preserving search engine rankings[L]tells Apache to stop processing any further rewrite rules after this one
For Nginx Servers
Edit your Nginx configuration file (usually located in /etc/nginx/sites-available/ or similar) and add a dedicated server block for your subdomain:
server { listen 80; server_name sub.example.com; # Redirect all requests immediately to the target URL return 301 http://example.com/photos; }
After saving the config, restart Nginx with sudo systemctl restart nginx to apply changes. This is a clean, efficient server-level redirect that avoids extra processing overhead.
Quick Verification Test
To confirm the redirect works as expected, run this command in your terminal:
curl -I http://sub.example.com/any/random/article-path
Look for a Location: http://example.com/photos header and a 301 Moved Permanently status code in the output—this means the redirect is functioning correctly.
内容的提问来源于stack exchange,提问作者user5017650

