Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess rewrite url like Stack Overflow

Stack Overflow generates rewrite URLs,

so i need to know how i can do it like Stack Overflow?

http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow => 200 ok.(without trailing slash)
http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow/ => 200 ok.(with trailing slash)
http://stackoverflow.com/questions/9168364/ => 301 redirect.
http://stackoverflow.com/questions/9168364  => 301 redirect.

How i can do it with mod_rewrite ?

i have something like this:

RewriteRule ^([0-9]+)[/]([^/]*) ./cat.php?id=$1&title=$2 [L,NC]



mydomain.com/999 => 404 not found.
mydomain.com/999/ => 200 ok.
mydomain.com/999/test => 200 ok.
mydomain.com/999/test/test2 => 200 ok.
mydomain.com/999/test/test2/test3 => 200 ok.
mydomain.com/999/test/test2/test3/test4 => 200 ok.

please let me know how i change RewriteRule ?

like image 548
UFO Avatar asked Dec 17 '25 13:12

UFO


2 Answers

You need to tweak your regex a bit by making trailing slash optional. Use this rule:

RewriteRule ^([0-9]+)(?:/([^/]*))?/?$ ./cat.php?id=$1&title=$2 [L,NC]
like image 98
anubhava Avatar answered Dec 20 '25 03:12

anubhava


.htaccess:

<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On

  # Get rid of index.php
  RewriteCond %{REQUEST_URI} /index\.php
  RewriteRule (.*) index.php?rewrite=2 [L,QSA]

  # Rewrite all directory-looking urls
  RewriteCond %{REQUEST_URI} /$
  RewriteRule (.*) index.php?rewrite=1 [L,QSA]

  # Try to route missing files
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} public\/ [OR]
  RewriteCond %{REQUEST_FILENAME} \.(jpg|gif|png|ico|flv|htm|html|php|css|js)$
  RewriteRule . - [L]

  # If the file doesn't exist, rewrite to index
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?rewrite=1 [L,QSA]

</IfModule>

index.php:

$url = $_SERVER['REQUEST_URI'];
$url = explode("/",substr($url,1));

Your links would be readable by PHP as follow:

http://www.website.com/First/Second/Third

$url[0] >> 'First'

$url[1] >> 'Second'

$url[2] >> 'Third'

like image 22
MaveRick Avatar answered Dec 20 '25 02:12

MaveRick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!