Htaccess code to remove id and title from URLs? [d

2019-09-07 01:22发布

This question already has an answer here:

I have used my .htaccess file to add www. to index url , remove .php and remove ?id= from URLs.

This is original url:

www.site.com/article.php?id=12&title=title-text

Url with .htaccess code

www.site.com/article/12

This code have removed &title=title-text from url.

How to remove &title= without title-text? Like this:

www.site.com/article/12/title-text

.htaccess file

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^ifeelvideos.com [NC]
RewriteRule ^(.*)$ http://www.ifeelvideos.com/$1 [L,R=301]

# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R,L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)/?$ $1.php?id=$2 [L,QSA]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L]

#Alternate default index pages
DirectoryIndex first.html index.htm index.html index.php

1条回答
别忘想泡老子
2楼-- · 2019-09-07 02:01

I am assuming that article.php doesn't actually need the title to operate, only the id. You can only add the title to the url if the title exists in the url in the first place. You can leave out the second rule if title is always in the url.

# To externally redirect /dir/foo.php?id=123&title=456 to /dir/123/456
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&]+)&title=([^&\s]+) [NC]
RewriteRule ^ %1/%2/%3? [R,L]

# To externally redirect /dir/foo.php?id=123 to /dir/123
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&\s]+)\s [NC]
RewriteRule ^ %1/%2? [R,L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)(/[^/]+)?/?$ $1.php?id=$2 [L,QSA]

Furthermore, article.php should check $_SERVER['REQUEST_URI'] and perform a redirect if the title is not in it:

<?php
  $id = intval( $_GET['id'] );
  $title = titleById( $id );

  $parsedurl = explode( "/", $url );
  if( $parsedurl[3] != $title ) {
    header( "Location: http://www.example.com/article/$id/$title", true, 301 );
    exit();
  }
查看更多
登录 后发表回答