How through .htaccess to make so that when entering on:

  • site.com/site worked handler site.php
  • site.com/test handler test.php worked
  • site.com/category/{dynamic-category-name} did the category.php handler work?
  • one
    You have already been answered many times, young man, myself included. Duplicate - read about routing and MVC and you will get an answer to your question. - Evgeny Ivanov
  • I find it difficult to understand what is written in the documentation. Can you show the simplest example? - asd
  • You do not need to read the documentation (forgive me, those who spend their lives on documentation descriptions), you just need to read google.com/… . And you will get answers to all the questions, and then, when you do not understand something, ask here. - Evgeny Ivanov
  • @ EvgenyIvanov what does MVC have to do with it? man has a question about htaccess. If I ask about the addition of natural numbers, then I don’t need to send me to google a textbook on mathematical analysis. - teran
  • This resource doesn’t welcome "think for me" questions. Where is the example that you tried, but it does not work? - iosp

1 answer 1

Can you show the simplest example?

For the first rule, the simplest mapping is the expression site/? where /? indicates an optional slash at the end of the line. To write the mapping of this pattern to the handler you need, you should use the RewriteRule directive.

The syntax of the directive, according to the documentation, is as follows ^

 RewriteRule Pattern Substitution [flags] 

where pattern is your url matching pattern, substitution is a replacement, i.e. where this request is forwarded. Next are the flags.
Most often, the flags L (stop viewing rules) and QSA (add original query parameters) are probably used.

it follows that the simplest example for your first URL will be

 RewriteRule ^site/?$ site.php [L, QSA] 

Obviously, for test , the rule will be the same. You can also write a general rule for these two expressions using groups and back links .

 RewriteRule ^(site|test)/?$ $1.php [L,QSA] 

Here in parentheses is the capture group, inside it | denotes или , and $1 in replacement means a link to this group (to the first group). Groups may be several.

To implement the last link, you will also need groups, but now the group name will fall into the group.

 RewriteRule ^category/(.*) category.php?cat=$1 [L,QSA] 

here denotes any character, and * - zero or more repetitions.