Htaccess code to remove id and title from URLs? [duplicate]

天大地大妈咪最大 提交于 2020-01-17 11:06:13

问题


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:


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();
  }


来源:https://stackoverflow.com/questions/29812211/htaccess-code-to-remove-id-and-title-from-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!