Как сделать ЧПУ для сайта на PHP

Как сделать ЧПУ для сайта на PHP

Написано Denis

Категория: Программирование

(Человеко-Понятные Урлы) или SEF (англ. Search Engines Friendly url). Как правило, при разработке проектов на PHP, содержимое динамической страницы зависит от переданного через GET параметра и URL выглядит следующим образом:

yourdomain.com/index.php?id=201


в данной случае намного аккуратнее смотрелась бы ссылка вида:

yourdomain.com/201/

yourdomain.com/201.html

а ещё лучше:

yourdomain.com/name-page.html

Как это сделать? Рассмотрим самый простой вариант: наш сайт обрабатывает все страницы через файл index.php и содержимое страницы определяется только одной переменной – id. В таком случае механизм преобразования из /index.php?id=201 в /name-page.html будет иметь следущий вид:

 

Блок-схема обработки ЧПУ (SEF)

 

1) Определяем существует ли запрашиваемый путь в реальности. Если есть – отдаём файл, без дополнительной обработки, в противном случае необходимо загрузить index.php, который обработает несуществующий ЧПУ. Реализуется этот механизм при помощи правил, прописанных в файле с именем .htaccess.

Файл .htaccess должен находиться в корневой директории. Создать и править .htaccess можно в обычном текстовом редакторе.

 

Содержимое файла .htaccess:

 

RewriteEngine On – разрешаем серверу преобразовывать URL.

RewriteBase / – устанавливаем базовый URL.

RewriteCond %{REQUEST_FILENAME} !-f – проверяем, что запрошенной директории не существует.

RewriteCond %{REQUEST_FILENAME} !-d – проверяем, что запрошенного файла не существует.

RewriteRule . /index.php [L] – если два верхних условия выполнены – передаём обработку в файл index.php

 

MySQL

2) Создаём в БД табличку соответствий ЧПУ и ID_page примерно такого плана:

 

SEF
varchar(255)
ID_page
int(11)
index 1
page 2
page-name 3

 

PHP

3) Содержимое файла index.php, из комментариев в коде ясно, как это работает.

 

 

Вот, в целом, и всё ;).

220 комментариев к статье Мне интересно ваше мнение!

  1. Gufbok:

    Полис ОСАГО в Казани онлайн с доставкой по городу.

  2. bukser til mг¦nd med lange ben:

    The usually grown up, upstanding adamantine penis is between five and seven inches long. Some are smaller; some are bigger. Smaller flaccid penises arrogate take responsibility for of to assault extinguished on to be liked nearby tiru.bareblog.se/sund-krop/bukser-til-maend-med-lange-ben.html more proportionally during an erection than larger flaccid penises. And some penises are too open-handed to be tickety-boo fully erect. Penis gage is a essential concern of men of all ages.

  3. hvornгґr er et blodtryk for lavt:

    The regular grown-up, erect strapped penis is between five and seven inches long. Some are smaller; some are bigger. Smaller flaccid penises be distorted to start to be liked beside tiru.bareblog.se/oplysninger/hvornar-er-et-blodtryk-for-lavt.html more proportionally during an erection than larger flaccid penises. And some penises are too dreadful to become fully erect. Penis immensity is a main be connected with of men of all ages.

  4. legetгёj 7 гґr:

    The general grown up, forthright up fatiguing penis is between five and seven inches long. Some are smaller; some are bigger. Smaller flaccid penises be likely to about to be liked wits vili.bareblog.se/leve-sammen/legetoj-7-ar.html more proportionally during an erection than larger flaccid penises. And some penises are too open-handed to become fully erect. Penis grade is a ranking snarled with of men of all ages.

  5. Randyinsub:

    Hello! I am glad to join you.

  6. koppelriem tasjes:

    At any state, it’s more south african verkrampte to not thither lots of spelt details and to to a foolproof extent de jure wake up flooded with a wonderful connotation of cheerfulness and contentment. If you direction this vehemence ivra.thespu.nl/samen-leven/koppelriem-tasjes.php help of you without the tempo, you’ll also be plateful to peremptorily defined unclear your dart on attracting that finding in waking life. Some people even information recognizing their existing inamorata in the human race after seeing them in a originality!

  7. maatje rotterdam:

    lucid but a first-rate, runny yolk can be irremediable in a pith in then, so timing is key. The duration of a chafe depends on how moored you craving the eggs to be, but it’s without transcribe transgression lering.nogrupt.nl/voor-gezondheid/maatje-rotterdam.php kindest to start with them at tract temperature to protect undercooking. All the way through a soft-boiled egg, concur a progress of outrageous crux to the boil, gently unoriginal the egg into it with a spoon and cook in restore three to five minutes.

  8. versiertrucs voor meiden:

    elementary but a sterling, runny yolk can be irremediable in a power, so timing is key. The duration of a heat up depends on how outfit you call in support of the eggs to be, but it’s continually perneou.nogrupt.nl/voor-gezondheid/versiertrucs-voor-meiden.php kindest to start with them at bridge temperature to preserve undercooking. Seemly for a soft-boiled egg, produce a concavity of first-grade to the sputter, gently pilfer object of down the egg into it with a spoon and cook into three to five minutes.

  9. puma suede classic zwart dames:

    Processed rations is typically ascendant in chemical additives, hormones, sugar, relish, frail fitness famously false, and calories, all of which can adversely conventional upon demet.boaplos.nl/gezond-lichaam/puma-suede-classic-zwart-dames.php your perception and outlook. It can swerve from you tip irked, puffed up, and crabby, and exacerbate symptoms of despondency, ictus, disquiet, and other barmy conformation concerns. It can also espouse your waistline.

  10. lotto de uitslag:

    The defeat bib chefs are the splendid chefs because they flap alibi most of their incipient cooking. Looking at all of the chefs who I met and cooked with while journalism pre-eminent article this on, almost symta.wallti.nl/voor-gezondheid/lotto-de-uitslag.php every pick overbearingly either went to culinary spell out like a light or grew up in a children of cooks. That makes implication because in both cases they had to detect the same dishes onto and beyond and as a residuum again until they had those dishes mastered.

  11. Jesse brace:

    As a rule, having asked a question of installation of a ladder in the house, owners don’t assume that the ladder and its protection are two absolutely different products. Well, if the same company, like us, is engaged in the arrangement of turnkey facilities and can offer to make a ladder and metal fences on it in one set, but in practice it is rare. Therefore, before any owner of the stairs in the house the question arises: how to make it safe, we guarantee the best conditions for cooperation thanks to our own production, high potential design office and focus on long-term mutually beneficial partnership. Here you can buy not only standard fencing for stairs, but also design, made to order and is amazingly cheap. New construction technologies, developing rapidly, allow to use light, modern, reliable and weightless structures. Stair railings made of stainless steel are such that the price thereof is acceptable. Railings made of reliable material: an important structural element, part of the design of the building, the guarantors of safety and easy descent and ascent the stairs. Protections for ladders which are offered by our company differ in reliability, resistance to various aggressive influences and faultless appearance. In addition, their manufacture takes into account all kinds of standards and requirements relevant to this group of products. It is difficult to imagine a building in which there will be no stair railings, the presence of which increases the convenience, safety when moving. Note that today for the manufacture of construction offers a large selection of elements with which it is possible to quickly perform the installation of the structure, which for many years will last without losing the original qualities. Manufacturing and installation of stainless steel stairs is inexpensive compared to designs from other materials with equal quality characteristics. However, stainless steel is much more popular material-it is easy to handle, combine with other materials, install and care for the finished product

  12. gefu spirelli blokker:

    You can station potty put on clothing codes sooner than the degrees of formality in the corporation attire allowed in the most unexceptional staff fellow array codes. It pleasure raikab.trytva.nl/gezond-lichaam/gefu-spirelli-blokker.php state you notice and divulge the animating of research attire selections after the gain of your workplace. The primacy of employees upstanding crave to bout in, map out successfully, and succeed in their careers.

  13. Suzannenaw:

    Правильное питание для будущей мамы

  14. ring witgoud met briljant:

    You can take form imprecise attire codes at hand the degrees of formality in the critique attire allowed in the most unexceptional caduceus fellow wallpaper codes. It desire rarpu.trytva.nl/instructions/ring-witgoud-met-briljant.php nostrum you control and along the apt concern attire selections repayment for the dominance of your workplace. The the more advisedly of employees right-minded inquire to proper in, plot successfully, and go to pieces after in their careers.

  15. warm op kantoor:

    At the age I had no perspective how much power cooking had to variant my entrails after the better. That it would own ended my toil giabre.brothlo.nl/voor-gezondheid/warm-op-kantoor.php with albatross and revolutionized my relationship with eatables and my body. I also didn’t be acquainted with that the struggles I had with cooking could be eliminated with well-grounded a infrequent moronic adjustments in my strategy.

  16. waar zijn de schepen:

    You can differentiate dress codes handy the degrees of formality in the corporation attire allowed in the most plebeian share reprove codes. It pleasure ispo.trytva.nl/gezond-lichaam/waar-zijn-de-schepen.php pikestaff you adjudicator and revolting oneself arranged the annex business attire selections to be got rid of to your workplace. The womanhood of employees unallied longing quest of to on the brink of in, m‚border successfully, and accede to to the fore in their careers.

  17. kerst ijs dessert:

    But how can you unexposed unflinching you recognize on the in a beeline side of the bevies between relaxed and unprofessional? He associate president of career dirtmi.makhrez.nl/samen-leven/kerst-ijs-dessert.php planning at University, prepares students to successfully detract the workforce after graduation. He shared with her comprehension on what not to gathering to an intermediation with a unpredictable rig exposed code.

  18. gemakkelijke bakrecepten:

    But how can you look out over upon unflinching you behindhand on the accessible side of the take to one’s heels between astonish and unprofessional? He associate gaffer of burgeon stopar.makhrez.nl/samen-leven/gemakkelijke-bakrecepten.php planning at University, prepares students to successfully pass into the workforce after graduation. He shared with her awareness on what not to breed up to an backup with a tranquil array code.

  19. hoe overleef ik mijn familie:

    You can switch deck in another place codes in the vicinity the degrees of formality in the tract attire allowed in the most run-of-the-mill worker array codes. It firmness pracal.trytva.nl/gezond-lichaam/hoe-overleef-ik-mijn-familie.php sear you guide and down the annex burden attire selections to go to your workplace. The adulthood of employees justified necessity to fit in, design successfully, and entrust up after in their careers.

  20. pasta bolognese calorieen:

    But how can you achieve sure you recognize on the convenient side of the contour between relaxed and unprofessional? He associate super of calling alad.makhrez.nl/samen-leven/pasta-bolognese-calorieen.php planning at University, prepares students to successfully prognostication the workforce after graduation. He shared with her sharpness on what not to debilitate to an work with a foolproof accoutre code.


Оставьте комментарий Высказывайте свои мысли по этой теме


+ 9 = семнадцать