未手动添加.php后缀时网页无法加载的问题求助
Hey there! Let's break down exactly what's happening here and walk through how to get those clean, suffix-free URLs working properly.
The Root Cause
When you visit https://classified.machela.org/post-ad, your web server has no idea it should map that request to post-ad.php—by default, servers only look for files that match the exact URL path you enter. Since there's no actual file named post-ad (only post-ad.php), it throws a "Not Found" error. This is almost always a problem with missing URL rewriting configuration or disabled automatic file suffix matching.
Fixes by Server Type
Let's cover the two most common web servers, Apache and Nginx:
For Apache Servers
Enable mod_rewrite (if not already on)
Most Linux-based Apache setups let you enable this module with a simple command:sudo a2enmod rewrite sudo systemctl restart apache2You can confirm it's enabled by checking a
phpinfo()page (look for themod_rewriteentry under "Loaded Modules").Add Rewrite Rules via .htaccess
Create or edit the.htaccessfile in your website's root directory, and add these rules:RewriteEngine On # Skip if the request is for an existing file or directory RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Append .php to the request and load that file RewriteRule ^(.*)$ $1.php [L]Note: Make sure your Apache site configuration has
AllowOverride Allset for your website's directory—otherwise,.htaccessfiles won't be processed.Alternative: Enable MultiViews
A simpler (but less flexible) option is to turn on Apache's MultiViews feature, which automatically matches requests to files with appropriate suffixes. Add this line to your.htaccess:Options +MultiViews
For Nginx Servers
Update Your Site Configuration
Open your Nginx site config file (usually located in/etc/nginx/sites-available/), and modify thelocation /block to include atry_filesdirective that checks for the.phpversion of the request:server { # ... existing server config (listen, root, server_name, etc.) ... location / { try_files $uri $uri/ $uri.php$is_args$args; } # Make sure your PHP processing location is also configured correctly location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Adjust PHP version as needed } }Restart Nginx
Apply the changes by restarting the Nginx service:sudo systemctl restart nginx
Quick Checks to Rule Out Other Issues
- Double-check that the
post-ad.phpfile exists in the correct directory on your server, and that file permissions are set properly (usually644for files,755for directories). - If you're using a CMS or framework, make sure its built-in URL rewriting isn't conflicting with your custom rules.
内容的提问来源于stack exchange,提问作者Humble Creation

