简体   繁体   中英

Change the .htaccess router, id to title

I am working with PHP. My htaccess looks like this:

RewriteEngine On
RewriteRule ^news/([a-zA-Z0-9_-]+)(|/)$ index.php?url=news&id=$1

#Redirecciones
#Redirect 301 / /index.php

# Quickregister Rules
ErrorDocument 404 /error.php

Right now to access the news in this case the route would be this:

http://localhost/news/3

And I want to change it to access some as follows

http://localhost/news/mi-noticia-nueva
http://localhost/news/mi-noticia-nueva/3

I have tried the following rewritrule without success:

RewriteRule ^news/(\d+/[\w-]+)$ index.php?url=news?id=$1 [NC,L,QSA]
RewriteRule ^news/([a-zA-Z]+)?$ index.php?url=news&name=$1 [L]
RewriteRule ^news/(.*)$ index.php?url=news&name=$1 [L]

You can use this rule:

RewriteRule ^(news)/(?:.*/)?(\d+)/?$ index.php?url=$1&id=$2 [L,QSA,NC]

This will support there URIs:

/news/mi-noticia-nueva/3
/news/3

Pattern used is:

  • ^ : Start
  • (news) : Match and group news
  • / : Match a /
  • (?:.*/)? : Match any test followed by a / . This is optional match
  • (\d+) : Match 1+ digits in capture group #2
  • /?$ : Match optional / before end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM