如何为网站创建自定义404页面?访问无效URL自动跳转
Hey there! Creating a custom 404 page that automatically loads for invalid URLs like http://example.com/anydummytext is totally straightforward—though the exact steps depend on your web server or hosting setup. Let me walk you through the most common scenarios:
1. Apache Web Server
If you're using Apache, here's how to set it up:
- First, design your custom 404 page (save it as
404.html) and drop it into your website's root directory. Add whatever makes sense—friendly text, links to your homepage, a search bar, even a silly meme to keep visitors engaged. - Next, open (or create) the
.htaccessfile in your root folder, and add this line:ErrorDocument 404 /404.html - That's all! Apache will now serve your custom page whenever someone hits a non-existent URL.
2. Nginx Web Server
For Nginx users, the process is just as simple:
- Create your
404.htmlfile in your site's root (or adjust the path below if you store it elsewhere). - Open your Nginx config file—usually found at
/etc/nginx/nginx.confor in/etc/nginx/sites-available/for your specific site. - Inside the
serverblock, add this line:error_page 404 /404.html; - Restart Nginx to apply changes. On most systems, run this command:
sudo systemctl restart nginx
3. Static Site Hosts (GitHub Pages, Netlify, Vercel, etc.)
Most static hosting platforms make this dead simple:
- Just create a
404.htmlfile in your site's root directory. The host will automatically detect it and serve it whenever a 404 error occurs. No extra config needed—just push the file to your repo or upload it to the platform.
4. PHP-Based Dynamic Sites
If your site runs on PHP, you have two options:
- Use the server-level config above (Apache/Nginx) which works perfectly with PHP sites.
- Or handle it directly in your code, especially if you use a front controller pattern (common in frameworks like WordPress, Laravel, etc.). For example, in your main
index.php:$requestedPath = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI']; // Check if the requested resource doesn't exist if (!file_exists($requestedPath) && !is_dir($requestedPath)) { header("HTTP/1.0 404 Not Found"); include('404.html'); // Or 404.php if you prefer PHP logic exit(); }
Quick Pro Tips
- Test it! Visit a dummy URL like
http://yourdomain.com/thisdoesnotexistto confirm your custom page loads. - Keep the 404 status code: Make sure your page returns a proper 404 HTTP status (not 200 OK). All the server methods above handle this automatically, but if you're using custom code, verify with Chrome DevTools' Network tab.
- Make it user-friendly: Help visitors get back on track with clear links, a search box, or a lighthearted message—don't leave them stranded!
内容的提问来源于stack exchange,提问作者user8769728
相关产品推荐
相关产品推荐

