.htaccess if URL is bad do something

2020-07-23 05:48发布

问题:

I'm making my personal CMS. I want to use in it cool (friendly) URLs. This is my .htaccess file code:

RewriteEngine on
RewriteBase /
DirectoryIndex index.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z-_0-9_/]+)/?$ index.php?args=$1 [L]

I see that on Stack Overflow friendly URLs are also used. Today I tried to make an error on Stack Overflow. To (for example) this URL http://stackoverflow.com/questions/5469955/htaccess-url-rewrite-if-file-not-exists. I added .php. But I didn't see a 404 error. Our forum in a magic method deleted my postscript and redirected me back to correct site URL. How can I make the same in my CMS?

I tried to change this (RewriteRule ^([a-zA-Z-_0-9_/]+)/?$ index.php?args=$1 [L]) line to (RewriteRule ^([a-zA-Z-_0-9_/]+)/([a-zA-Z-_0-9)$ index.php?args=$1 [L]), but this isn't helpful and then I see 500 Internal Server Error.

回答1:

If you need to have the same behavior as Stack Overflow then you got to have some server-side support (e.g. PHP, ASP, etc.) as well. Consider the following code snippet:

.htaccess:

RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?id=$1&title=$2 [L,NC,QSA]

index.php:

<?php
   $id    = $_GET['id'];
   $title = $_GET['title'];

   $dbTitle = // Get title from Database query using $id
   ...
   if ($title != $dbTitle) {
      // Redirect with 301 to correct /<id>/<title> page
      header ('HTTP/1.1 301 Moved Permanently');
      header('Location: /' . $id . '/' . $dbTitle);
      exit;
   }
   // The rest of your script
?>