ANTICHAT.XYZ    VIDEO.ANTICHAT.XYZ    НОВЫЕ СООБЩЕНИЯ    ФОРУМ  
Баннер 1   Баннер 2
Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей. Здесь обсуждаются безопасность, программирование, технологии и многое другое. Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
Вернуться   Форум АНТИЧАТ > Оффтоп > Forum for discussion of ANTICHAT
   
Ответ
 
Опции темы Поиск в этой теме Опции просмотра

[Translation] Mod_Rewrite tutorial
  #1  
Старый 13.03.2007, 19:32
Аватар для Дрэгги
Дрэгги
Moderator - Level 7
Регистрация: 26.08.2005
Сообщений: 457
Провел на форуме:
4007686

Репутация: 1442
По умолчанию [Translation] Mod_Rewrite tutorial

mod_rewrite...what is it? As wiki says -

Цитата:
A rewrite engine is a piece of web server software used to modify URLs, for a variety of purposes.
i.e. some kind of module for a web server, enabling to modify links...In general, the rewrite engine itself exists both for apache and microsoft's IIS and even for java platforms =) In this particular article we're going to talk exactly about mod_rewrite for apache.

Everything we're gonna need is .htaccess file radically, if you already have it..then it's only need to finish writing some certain lines in it..and surely in case hoster hasn't installed this module yet, he should be kicked around a little..)

As for me personally I use full links in .htaccess, if you want to use relative links like /index.php?blabla=31337 then it's advisable to include the following lines in the file, which ,even though only a little bit, but speeds up the work

Цитата:
DocumentRoot /home/htdocs/www
<Directory /> Options FollowSymLinks
</Directory>
that is, in case you have a www site but the option isn't on then apache will be trying to find Index.php file first in /home/ then in /home/htdocs/ and in the end will stumble on /home/htdocs/www/index.php. This is nothing of course, but you'll still spare some hundredth parts of the second..) or you can write in every file before "rewrital on" the following phrase

PHP CODE:


Цитата:
Options +FollowSymLinks


Generally it is possible to find many ways to use in it..most popular of which - is the transformation of the link into some more readable look ) ..well, find me a man who would like the link such as

Цитата:
http://site.com/index.php?action=forum&forum=theme01
Let us transform it into..for instance

Цитата:
http://site.com/forum/someshit.htm

For this we will need to turn RewriteEngine itself on for starters:

PHP CODE:

Цитата:
RewriteEngine On
then we overwrite the url itself:


PHP CODE:

Цитата:
RewriteRule ^ ([a-z]+)/([a-z0-9]+).htm$ index.php?action=$1;forum=$2
Let's clarify things related to this quite simple construction...

RewriteRule simply sets the beginning of the overwrite line.

([a-z]+) indicates that everything before "slash" is replaced with small roman letters from a to z (everything is written into the $1 variable)

then after "slash" we see ([a-z0-9]+).htm
, that is, here we replace everything after "slash" with small roman letters from a to z and digits from 0 to 9 ($2 variable)
, and then add htm extension in the end of the url.

As you understand, such .htm files never actually were and will never be on your site, it's just that thus links are shown in a more comfortable way.

The most important here is to remember this order - how it goes after RewriteRule - firstly - how to transform and only then what to transform


As you understand that's in order to make forum fully overwrite links (urls) with parameters in htm look (not obligatory htm, it can be any kind of extension your imagination might create) for all existing transferrable by GET parameters...should it be a search, threads, forums, personal messages after all...the main thing is also not to overdo it = )

Original copyright: blackybr

English version translation: Дрэгги

Последний раз редактировалось Дрэгги; 05.04.2007 в 18:53..
 
Ответить с цитированием

  #2  
Старый 14.03.2007, 01:01
Аватар для NeMiNeM
NeMiNeM
Постоянный
Регистрация: 22.08.2005
Сообщений: 540
Провел на форуме:
4372175

Репутация: 1221


По умолчанию

Good. The only big mistake I've noticed is when we speak about file types(I mean .htm .exe .doc etc) we say extensions not expansions. (expansion is mainly a physical term).
And I've checked the original article, there is not so many information left, so please don't create a new thread "part two" but add that here. Thank you.

+5
 
Ответить с цитированием

  #3  
Старый 19.03.2007, 00:58
Аватар для Дрэгги
Дрэгги
Moderator - Level 7
Регистрация: 26.08.2005
Сообщений: 457
Провел на форуме:
4007686

Репутация: 1442
По умолчанию

Let's have a look at another example (here I already use relative links), let's make out of this

Цитата:
http://site.com?index.php?forum=someshit&nickname=hacker& userID=31337
rewriting it into

Цитата:
http://site.com/someshit/31337-hacker.htm
Firstly, as I have mentioned above, enable

PHP code:

Цитата:
Options +FollowSymLinks
then


PHP code:

Цитата:
RewriteEngine On
RewriteRule ^([^/]+)/([0-9])-(.+).htm$ index.php?forum=$1&nickname=$2&userID=$3
First line is understandable let's have a closer look into the second one. ([^/]+) - before "slash"
we allow the use of any symbols (imagine we will have a digit in our forum title...though something like ([a-zA-Z0-9]+) is possible, but here however the dash won't be displayed).

After ([0-9])-(.+) that is, in the second part of the "final file" we insert the variable $2 itself (which is an equal to "hacker"), and in the first one we insert only digits (in our case it is, for instance, the user ID which is an equal to 31337 ( ([0-9]) ). And certainly we add an extension in the end. The second part of the line needs no comments. . i.e there it's only indicated what is to rewrite. All three variables' values.

I'll go over explaining the regular variables themselves once more:


Цитата:
[a-z] - the lower Roman letters

[A-Z] - the capital Roman letters

[0-9] - digits

by the way... you may also use [c-y] or [4-8] that is any letters/digits range.

^ - it has two ways of use.

1) when it is inside of the square brackets it means the denial, i.e [^ab123] means that the replacement will take place with the use of any symbols except a,b,1,2,3


2) means the start of the "regular" thing (Ex. RewriteRule ^ /*expression*/)


dot is any kind of the single symbol

+ - the use of the one or more than one symbol and may be used only with [blablabla] (Ex. [0-9+] that is the rewrite will be processed by one or more symbols from 0 to 9)

? - the same things as "+", however none at all or just one indicated symbol is used.


* - rather ineffective variable from my point of view. But still its point is figuratively speaking to replace with whatever comes to hand )


$ - the end of the line. In general it works without it nonetheless.


% - sets the variable incoming from from RewriteCond (keep reading about it further below)


In addition to this the RewriteCond may be used, that is not the rule of the rewrite is set, but the CONDITION (!!!).
They have similar syntax.


what we can do to them... let's look into it using this example:


PHP code:

Цитата:
RewriteRule ^(forum)/(topicID)$ /read-$1-topic-$2
Moreover, this arises


PHP code:

Цитата:
read-#forum-and-#topicID

where #forum is forum's title, #topicID is the ID of the topic.


All the variables are given number in accordance with their appearance and the condition and the rule both have 2 variables (in this particular example naturally they have, but generally speaking even one hundred if you like, no one prevents you from doing this), which are being set by round brackets, because in order to use them you'll need to put them in there where they are exactly needed by you in the final link-result.


Let's combine both the rule and the condition:

Цитата:
RewriteCond %{CONDITION_STUFF} ^(forumname)/directory/(topicID)
RewriteRule ^(forumname)/directory/(topicID)$ /our_forum-$1-topic-%2

By this we'll rewrite the link with the numerous parameters into the following type

PHP code:


Цитата:
forumname-forum-topicID

In general it'll do even without "slashes", but IMHO the inscriptions will merge = )


Here I've had in mind quite funny regular thing like this:


PHP code:


Цитата:
RewriteRule ^([^.]+)$ /index.php

Don't you find it a little weird upon reading? = ) You're right...it rewrites everything based on a rule everything except any kind of symbol, I myself haven't tried it yet, but whoever checks what apache will spit out upon this one please ..requesting to write it here = )

So.. We've learnt how to use RewriteRule and RewriteCond, using mod rewrite in order to provide the safety of the server (for example from sql inj) and simply using it in order to decorate and memorize the links.

Thank you for reading

2nd part coming up

Original copyright: blackybr

Последний раз редактировалось Дрэгги; 19.03.2007 в 01:01..
 
Ответить с цитированием

  #4  
Старый 19.03.2007, 15:44
Аватар для Talisman
Talisman
Постоянный
Регистрация: 22.04.2006
Сообщений: 566
Провел на форуме:
1325772

Репутация: 517


Отправить сообщение для Talisman с помощью ICQ
По умолчанию

PHP code:
Цитата:
RewriteRule ^([^.]+)$ /index.php

WHY this cod is php??? its cod from .htaccess file! apache-file!
 
Ответить с цитированием

Mod Rewrite Tutorial Part3
  #5  
Старый 04.04.2007, 23:27
Аватар для Дрэгги
Дрэгги
Moderator - Level 7
Регистрация: 26.08.2005
Сообщений: 457
Провел на форуме:
4007686

Репутация: 1442
По умолчанию Mod Rewrite Tutorial Part3

A few words about how it is possible to use mod rewrite in order to increase the security of a site, as well as for content, access rights limitations etc. and so on (without using web programming languages).
What else is mod rewrite capable of? Well it can do quite a lot of things. As I mentioned above, RewriteCond
determines the rules of a condition and always
preceds the RewriteRule , i.e the RewriteRule in this case works only under a true condition. Rewrite module accepts server variables as well which is undoubtedly pleasing. )

Here are some of them which have to be used quite often:

HTTP_USER_AGENT - the user agent (for instance Opera/9.10 (Windows NT 5.1; U; ru))

HTTP_REFERER - referer (i.e., a site which you came from to an original, final site)

HTTP_COOKIE - cookies being transferred =)

HTTP_FORWARDED - the address of the user who is currently on the page

HTTP_HOST - the address of a site (without http: //)


HTTP_PROXY_CONNECTION - set in the event when the client has come via "transparent proxy-server

HTTP_ACCEPT - a more precise definition of the informatio type (the so-called media-types) accepted by a browser on the given page, for example text/plain, text/html, image/gif, image/jpeg)


REMOTE_ADDR - your ip-address

REQUEST_METHOD - a method used for the delivery of the inquiry (GET, PUT, POST and so on)


SCRIPT_FILENAME - a full way to an executable script on the server


PATH_INFO - everything following the name of a script being initiated


QUERY_STRING - the line of an inquiry




Let's assume that we have certain site: http://site.com
For some reason we totally don't want certain someone to have access to some file type, for instance, pictures jpg, png (well meaning that only scripts could do it). It is possible to try to do it by means of mod_access, something having .htaccess of sorts in its content root:

PHP CODE:

Цитата:
<FilesMatch "\.(jpg|png)$">
Order Deny,Allow
Deny from all
</FilesMatch>
Well, the defect here is that it will forbid the access for both you and scripts triggering/opening pictures. We do it with the help of mod_rewrite:


PHP CODE:


Цитата:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_REFERER} .
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site\.com(/.*)?$
RewriteRule .(jpg|png)$

First two lines here are clear. Further along we see a condition - when HTTP_REFERER contains site.com (regular variables see above) then the viewing of a picture is allowed.

When can it be helpful? Well let's suppose we have a photoarchive and there is a counter and we wish to know the exact number of visitors. But actually when the photo is indexed in a search engine, and the person follows the link from that same yandex - in "referer" the yandex itself is indicated and it's not for the fact that the link will be directly on a picture. The so-called hot-linking. I think it is understandable



Now let's make an authorization of sorts. Using Mod_rewrite again of course..
Since I have already told that we shall not use php, perl etc. we will have to manage without the database as well =)


For this purpose let us investigate one more directive of Mod - the RewriteMap which is used in the rules concerning the replacement by different mapping functions relative to different correspondence areas with the help of the rewrite rule via rewritecond..


The authorization we will process through the sessions file in auth.txt which is situated outside of WWW. Let us assume that the full way on the server to the site is /home/user/www/

Let's create a file /home/user/auth.txt having this kind of content:


PHP CODE:


Цитата:
# session 1
abcdefghijkl 1

Moving further along let's see what we will have inside the .htaccess


PHP CODE:


Цитата:
Options +FollowSymLinks
RewriteEngine On
RewriteMap sessionids txt:/home/user/auth.txt

# there is no session at all
RewriteCond %{QUERY_STRING} !^(.*&)?sessionid= [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*&)?sessionid=(&.*)?$ [NC]
RewriteRule .* - [F,L]

# there's no session in the file
RewriteCond %{QUERY_STRING} ^(.*&)?sessionid=([^&]+)(&.*)?$ [NC]
RewriteCond ${sessionids:%2|0} ^0$
RewriteRule .* - [F,L]

or for a file looking like (let's use a more secured version - session + IP)


PHP CODE:



Цитата:
# session-ip 1
blablbalbalb-127.0.0.1 1


we'll get a slightly different result


PHP CODE:


Цитата:
RewriteCond %{QUERY_STRING} ^(.*&)?sessionid=([^&]+)(&.*)?$ [NC]
RewriteCond %2-%{REMOTE_ADDR} ^(.+)$ RewriteCond ${sessionids:%1|0} ^0$
RewriteRule .* - [F,L]



Everything which is done here I have already described. I'll repeat one more time -


We take the QUERY_STRING (i.e. the line of an inquiry) and verify whether it has the session through the .txt file (the same can be done through the .php file addressing the database which will yield the same results).



RewriteCond%2-%{REMOTE_ADDR} ^(.+)$ - %2 is taken from the first RewriteCond, our session at first, then the variable of the session and the IP-address (we have it in the .txt file too) - all of it we include in one variable - %1




RewriteCond ${sessionids:%1|0} ^0$




${sessionids:%1|0} - the verification on RewriteMap

sessionid - the name of the Rewrite Map itself



%1 - the variable which I have already mentioned above


0 - just the default variable


The gist of it is that in case the verification on the file returns the positive result and the line with the data exists for the Rewite Map in question, then 1 is returned (that exact "one" I put in the end of every line in the file) auth.txt, in the opposite case 0 is returned ( ^0$ means something like "let's associate 0 with it"). If the verification didn't take place at all, then still the same - 0 is returned, after which mod rewrite goes on with its work, having sent Forbidden ( [F] ) first.


(c) blackybr


Also see http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
http://en.wikipedia.org/wiki/Rewrite_engine




English version translation: Дрэгги

Последний раз редактировалось Дрэгги; 05.04.2007 в 12:32..
 
Ответить с цитированием

  #6  
Старый 05.04.2007, 03:45
Аватар для KPOT_f!nd
KPOT_f!nd
Познавший АНТИЧАТ
Регистрация: 25.08.2006
Сообщений: 1,524
Провел на форуме:
3405508

Репутация: 1745


По умолчанию

Дрегги - very good, as I have understood this translation of the article blackybr
throw up the russian original article? please!
 
Ответить с цитированием

  #7  
Старый 05.04.2007, 12:35
Аватар для Дрэгги
Дрэгги
Moderator - Level 7
Регистрация: 26.08.2005
Сообщений: 457
Провел на форуме:
4007686

Репутация: 1442
По умолчанию

Russian original article you say? Sheesh, you could've easily found it by using search. Anyway, here's the original: http://forum.antichat.ru/thread27498-mod+rewrite.html
 
Ответить с цитированием

  #8  
Старый 05.04.2007, 17:02
Аватар для NeMiNeM
NeMiNeM
Постоянный
Регистрация: 22.08.2005
Сообщений: 540
Провел на форуме:
4372175

Репутация: 1221


По умолчанию

Цитата:
Сообщение от Дрэгги  
Russian original article you say? Sheesh, you could've easily found it by using search. Anyway, here's the original: http://forum.antichat.ru/thread27498-mod+rewrite.html

In this case, next time please write not only the nickname of the author but also give the link to the original article.
And why don't you correct the mistakes I tell you? (e.g. "expansion" in the first post). And could you mark the main terms and keywords with special colours (like you did in the first part)? It would make your articles easier to read.

Anyway, thank you for the translation. Good job.
+7
 
Ответить с цитированием

  #9  
Старый 05.04.2007, 19:01
Аватар для Дрэгги
Дрэгги
Moderator - Level 7
Регистрация: 26.08.2005
Сообщений: 457
Провел на форуме:
4007686

Репутация: 1442
По умолчанию

Цитата:
And why don't you correct the mistakes I tell you?
Alright alright already Mr.English teacher. *rolls eyes* I forgot or was too lazy.

Цитата:
And could you mark the main terms and keywords with special colours (like you did in the first part)?
Ummm..I'm not sure...I thought I'd leave that up to you. I basically left everything the same way as it was in the original article except the colours inside php-code thingies. Do you know how to make the php-code quotes look the same as they were in that article? Also me not using colours means that the author didn't use them either.

Последний раз редактировалось Дрэгги; 05.04.2007 в 19:03..
 
Ответить с цитированием

  #10  
Старый 05.04.2007, 19:29
Аватар для NeMiNeM
NeMiNeM
Постоянный
Регистрация: 22.08.2005
Сообщений: 540
Провел на форуме:
4372175

Репутация: 1221


По умолчанию

Цитата:
Alright alright already Mr.English teacher. *rolls eyes* I forgot or was too lazy.
I'm not going to teach you English=) You've already got your diploma and you are on a higher level than I am. I haven't got any degree yet so it's you who can teach me, correct or give tips It's just quite strange for me that a person is lazy to correct his own mistakes... But let's stop this "flame" and offtop.
Цитата:
Do you know how to make the php-code quotes look the same as they were in that article?
Easy.
[*PHP][*/PHP]. This tag can be found on the bar together with quote,code,html etc tags.

Цитата:
Also me not using colours means that the author didn't use them either.
Sure. It's up to you. It was just an advice.
 
Ответить с цитированием
Ответ



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
[Translation] New Benchmark alternative or effective blind SQL-injection by Elekt NeMiNeM Forum for discussion of ANTICHAT 2 14.09.2007 19:43
[Translation] From sql-injection to root by p-range NeMiNeM Forum for discussion of ANTICHAT 0 20.04.2007 23:41
Hacking IIS Tutorial bxN5 Forum for discussion of ANTICHAT 1 14.03.2007 23:44



Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT.XYZ