halfer / php-tutorial-text

The chapter text for the "I ♥ PHP" project
14 stars 1 forks source link

Can we improve description of mod_rewrite rules? #11

Closed halfer closed 9 years ago

halfer commented 10 years ago

A Reddit reader has been in touch to ask for more information about the .htaccess rules to prevent access to site resources. The explanation was kept deliberately quite light here, since there is enough to be getting on with already.

However I might be able to do something in a sidebar, while making it plain that the material can be skipped. Here is a snippet of my reply to the reader:

RewriteCond %{REQUEST_URI} ^/(data|lib|templates|vendor)/
RewriteRule ^ - [L,R=404]

The first one sets up a condition (i.e. when the rule will apply) and the second one does the action.

So the condition is looking at a placeholder known as %{REQUEST_URI}. This is the URL of the page, relative to the domain. So it will always start with '/' and then it will contain the address, e.g. '/styles/assets/main.css' or '/install.php'. However there are some resources we want users specifically not to access directly.

These ones are in the data/lib/templates/vendor folders, so we add those into the second part of this command. The bar character means "or" and the ^ means "begins with". This format is known as a regular expression, and is a popular way of testing strings for certain conditions.

The RewriteRule basically says if you get a match, then this is the (L) last rule (i.e. don't process any more rules) and the server should (R) redirect to a 404 page (i.e. not found).

This is at the bottom of chapter 7.

halfer commented 9 years ago

This is done. Since it isn't a critical update, I've merged it with the latest text branch (v3) rather than creating a new one.