在Digital Ocean的Nginx服务器中隐藏URL的.html扩展名遇404/505错误求助
Hey there! I see you tried a PHP extension removal guide which didn't pan out—no worries, hiding .html extensions needs a tailored Nginx config setup. Let's walk through this step by step to get it working without those frustrating 404 or 505 errors.
Step 1: Locate Your Nginx Site Configuration
First, SSH into your DigitalOcean droplet and find your site's config file. It’s usually stored in one of these paths:
/etc/nginx/sites-available/your-domain.com(linked tosites-enabledfor active sites)/etc/nginx/conf.d/your-domain.conf
Open it with an editor like nano:
sudo nano /etc/nginx/sites-available/your-domain.com
Step 2: Add the Correct Rules for .html Extension Hiding
Inside your server block, replace or add the following rules. I’ll break down each part so you know exactly what’s happening:
# Optional: Redirect existing .html URLs to clean versions (great for SEO) rewrite ^/(.*)\.html$ /$1 permanent; # Serve clean URLs by checking for matching .html files location / { try_files $uri $uri.html $uri/ =404; }
What these lines do:
- The
rewriterule sends a permanent (301) redirect for any URL ending with.htmlto the same path without the extension. This keeps existing links working and helps with search rankings. - The
try_filesdirective tells Nginx to:- First try serving the exact URI as-is (e.g.,
/about). - If that doesn’t exist, try appending
.html(so it loads/about.htmlbehind the scenes). - If neither exists, return a proper 404 error.
- First try serving the exact URI as-is (e.g.,
Step 3: Fix Common Issues That Cause 404/505 Errors
- Verify your root directory: Make sure the
rootdirective in yourserverblock points to the correct folder where your HTML files live (e.g.,root /var/www/your-domain.com/html;). A wrong path is a top cause of 404s. - Remove conflicting rules: If you have leftover PHP extension removal rules from your earlier attempt, comment them out or delete them to avoid config conflicts.
- Test before restarting: Always validate your Nginx config to catch syntax errors that trigger 505s:
If you see "test is successful", reload Nginx to apply changes:sudo nginx -tsudo systemctl reload nginx
Step 4: Test the Setup
Visit your site using a clean URL (e.g., your-domain.com/about instead of your-domain.com/about.html). It should load the corresponding HTML file without showing the extension. If you still get a 404, double-check that the .html file exists in your root directory (Nginx is case-sensitive

