How to configure . htaccess to accept a hyphen in the URL?

Asked

Viewed 1,322 times

6

I’m customizing the Urls on my site, but the .htaccess does not accept hyphens Urls, for example:

postagem/1/criando-efeito-fadeout-com-javascript

When I write the title without the hyphens it works, but with them it doesn’t, why? How do I fix it?

My rule of .htaccess is written as follows:

RewriteRule ^postagem/([0-9]+)(/([a-z]+)/)?$ ler.php?post=$1&titulo=$2 [NC,L]

1 answer

5


Its regular expression contains the excerpt [a-z], defining that only letters are accepted.

Add the hyphen as follows: [a-z\-]. You get the expression:

RewriteRule ^postagem/([0-9]+)(/([a-z\-]+)/)?$ ler.php?post=$1&titulo=$2 [NC,L]

Optionally, you could include numbers like this:

RewriteRule ^postagem/([0-9]+)(/([a-z0-9\-]+)/)?$ ler.php?post=$1&titulo=$2 [NC,L]

Note: as the hyphen is a special character for regular expression, I added a bar ( ) from escape.

  • 2

    I guess I missed the exhaust to show up in the answer :)

  • @Bacco didn’t know that the backslash was a special character!

  • 2

    As a matter of fact, neither do I, but that’s ironic, it’s :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.