How to customize htaccess-friendly url by passing only Slug as visible parameter?

Asked

Viewed 157 times

0

Hello,

I seek to customize the friendly url more this way www.portalvidapet.com.br/radium-hotel-em-guarapari without having to pass another parameter visible in the url.

For that, I tried to do the .htaccess as follows: RewriteRule ^/([[a-z0-9-]+)/?$ texto.php?id=$1 [NC] , however, gives error 404.

If I do RewriteRule ^artigo/([[a-z0-9-]+)/?$ texto.php?id=$1 [NC] works perfectly, only I wouldn’t want to use the name artigo at the url, because, I would like to pass slug.

To look like this www.portalvidapet.com.br/radium-hotel-em-guarapari

How to solve?

1 answer

1


It seems to me that your htaccess rule has a syntax error my friend.

You did :

Rewriterule /([[a-Z0-9-]+)/? $ text.php? id=$1 [NC]

Is opening a [ without closing it, the right would be:

RewriteRule ^([a-z0-9-]+)\/?$ texto.php?id=$1 [NC]

That is any url that starts in the range containing the characters of a - z , 0 to 9 and -. May have one or more characters preceded by a bar or not. Assign to argument id on the page php text.

Do not forget to use backslash for / use. The slider is a special character of the regular expression so we must escape it. =)

I hope it helps you!

Testing the rule: inserir a descrição da imagem aqui Use the online test tool: https://htaccess.madewithlove.be/

  • It worked very well, now I have another problem, how to capture dynamically the id of the news via htaccess? 'Cause I need this information so that page texto.php give me the right result.

  • 1

    If you want to access the variable you passed per parameter, just use the global scope variable $_GET['id'] to access it within the test.php page. Try printing it like this <?php echo $_GET['id']; ? > at the top of the page.

  • In this case my url will be www.portalvidapet.com.br/radium-hotel-em-guarapari the ideal is to search for the slug? Or the correct is for me to pass the parameter with the urlid plus the slug?

  • 1

    Both ways are correct. But note that if you are only going to use Slug in your database in the table where you save your posts the Slug attribute of the table has to contain a (single) Unique key so there is no duplication. If you choose to use Slug you must have a php routine so that you can access the test.php page and load the id and other necessary information through this method. But that’s the answer to another question!

Browser other questions tagged

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