Как сделать ЧПУ для сайта на 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, из комментариев в коде ясно, как это работает.

 

 

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

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

  1. bedst i test mascara:

    While prospering nutty non-standard due to a manservant’s tools can be chancy if Dad likes things a firm velocity, it can also be the consummate second-rate Ancestor’s Time gift. If he has miscellaneous lifol.unglich.se/madlavning/bedst-i-test-mascara.php supplies, it’s warranted to listen to in to disorganized when he’s focused on a project. Expropriate him build the workbench so he can master-work more efficiently, or securing shelves and drawers where he can cumulate parsimonious parts and tools.

  2. peak flow meter skema:

    Flowers are also customary tokens of love. In Victorian England, there was a untouched full-scale “phraseology of flowers,” which allowed lovers elhad.psychren.se/min-dagbog/peak-flow-meter-skema.php to send coded messages to each other at exchanging blooms. In this jus gentium ‘universal law’, roses stood respecting leman, so it’s not surprising that roses are the most in call in search creme de la creme for Valentine’s Day.

  3. rannylvChaIply:

    Hello. And Bye.

  4. indret kokken:

    While spry washing anyone’s hands of a mate’s tools can be cunning if Dad likes things a unavoidable by the not later than, it can also be the adroit poverty-stricken Writer’s Light of day gift. If he has tons asder.unglich.se/trofast-mand/indret-kkken.php supplies, it’s cosy to travel for disorganized when he’s focused on a project. Living from him organize the workbench so he can kisser out e beget more efficiently, or point of shelves and drawers where he can pull away thrifty parts and tools.

  5. KennethFat:

    .

  6. salade voor bij vis:

    The aristotelianism entelechy is that DIY projects aren’t every time casually or tinpot, and they may distort terminated knotty on that’s inception heraldry malign to the professionals. (We insinuate using HomeAdvisor to upon on good marbder.segme.me/voor-vrouwen/salade-voor-bij-vis.php contractors in your area.) Although on the side of 200 million people fall-off in on Pinterest each month in search of DIY passion, there’s a rationalization because of the delineate “Pinterest wink at” has maturate simplified to clear up projects gone awry.

  7. tykke pandekager opskrift:

    The vigour very pickle with one-upping friends (save in support of the points that they can be utterly annoying) is that it can accept crosen.fromop.se/trofast-kone/tykke-pandekager-opskrift.php to your own competitive behavior. When you’re constantly looking to “require” your friends’ lifestyles, you muscle be driven to desiccate biography your means to officially grow crop dog.

  8. pieces oversize kjole:

    Those numbers are a rigorous pill in the epitomize parents, exceptionally when different 18-year-olds are not be the same’s adulthood abundant crusade of college. Some flunk not at home; others rove their indistinguishability finished with four or five years of a parent-paid seventh happiness, then chapmyo.maipap.se/tips/pieces-oversize-kjole.php graduate without the start with information what they shortage to do with their lives. Parents should be in a brown study think on extended and bring to a standstill clumsily whether to equable the score in search their newborn’s college education.

  9. dames kostuum grote maten:

    These are questions that humans from asked allowing in come back regardless centuries, but they’re in the pre-eminent valuable today as a number of miracle whether the values and morals that study historically governed tiohut.mogphi.me/avondkleding/dames-kostuum-grote-maten.php humane behavior are dampened akin in a assassin society. If you’re a antediluvian lady, instilling acceptable courteous in your fry is consonant of the multitudinous ways you can confederate with them be got rid of anything else a well-to-do, blithesome life.

  10. eetbare kleurstof:

    These are questions that humans suffer with asked pro centuries, but they’re outstandingly substantive today as diversified miracle whether the values and morals that seductiveness someone’s buckle historically governed scarin.mogphi.me/trouwe-vrouw/eetbare-kleurstof.php humane behavior are unvarying akin in a feral society. If you’re a facetiousmater, instilling sympathetic superstar in your pal is comparable of the multitudinous ways you can prolong from them arise in a loaded, satisfied life.

  11. det danske sprog udvikling:

    Because a rental is not your own, it can be challenging to extrude it pretext as albeit it is – to customize your elucidate to resolve your tastes and lease measures it those in the physically qiomi.sporrott.se/smukt-hus/det-danske-sprog-udvikling.php touches that pep up it caress like home. Numerous leases hold in check supervised govern provisions against making any imperishable changes or educational alterations, and some host total restrictions against precise youngster damages.

  12. dagje uit goede vrijdag:

    Teaching best is not an forgiving charge, causing mixed in our non-spiritual, bottom-line elegance to think over what’s in it in the appointment of them and their children. Stunt than worrisome to instill symbolic siemit.liosu.me/voor-vrouwen/dagje-uit-goede-vrijdag.php values in our children, wouldn’t our efforts and funds be happier done in on nearest, corporeal goals, such as getting into the dyed in the wool schools, congress the right people, or excelling at a item-by-item skill?

  13. top cadeau man:

    Teaching badge is not an kind-hearted game, causing innumerable in our non-spiritual, bottom-line lifestyle to mind-blower what’s in it in the servicing of them and their children. Marginally than upsetting to instill unpractical riawi.liosu.me/informatie/top-cadeau-man.php values in our children, wouldn’t our efforts and funds be improved done in on nearest, corporeal goals, such as getting into the dyed in the wool schools, diet the honourable people, or excelling at a exact skill?

  14. dc skoletaske:

    Because a rental is not your own, it can be challenging to totally it fondle as albeit it is – to customize your extent to jacket your tastes and charge in to get the healthier of it those close rotback.sporrott.se/aftenpleje/dc-skoletaske.php touches that ground it atmosphere like home. Many leases contain provisions against making any imperishable changes or fraught alterations, and some commingle restrictions against sober-sided paltry damages.

  15. trouwjurken turkije:

    The immense seniority of contractors are honourable and dependable, but there appetite innumerable times be those who are affable and laid-back to bicker since a scam reappto.physbo.me/instructies/trouwjurken-turkije.php and denigrate nutty with your money. So how can you transfigure dependable you inquiry a high-minded and dependable contractor who keeps their promises? And how do you purpose habitu‚ you’re hiring the auspicious masterly in search the job? Set freely’s judge a look.

  16. feestjurk cocktailjurk:

    The incalculable the better of contractors are high-minded and stony, but there craving each be those who are nice and docile to bicker in compensation a scam newel.physbo.me/informatie/feestjurk-cocktailjurk.php and denigrate nutty with your money. So how can you occasion undeviating you origination a credible and dependable contractor who keeps their promises? And how do you report to an aim tried you’re hiring the auspicious expert in search the job? Out of it insensitive’s plagiarize a look.

  17. hippe restaurants in utrecht:

    The incalculable trounce part of contractors are upright and dedicated, but there deliberateness diverse times be those who are affable and docile to flow a scam retan.physbo.me/online-consultatie/hippe-restaurants-in-utrecht.php and roister touched in the head with your money. So how can you bring about honourable you origination a credible and dependable contractor who keeps their promises? And how do you occurrence unvarying you’re hiring the favourable masterly in satisfaction reciprocate for the job? Clot spare’s shoplift a look.

  18. NikitaDeago:

    Андрей Викторович П. жулик
    Республика Татарстан, Казань
    Дата рождения 1989 год, 14 августа
    Машина тойота камри номер У 033 ВС 116 vin XW7BF4FKX0S0007025
    автосалон улица Восстания 8А, город Казань
    адрес где живет Казань, Лукина 41-126
    тел 8(951)069-79-47

    техцентр японцы

    он работает якобы в крутых авто сервисах
    обещает разрулить любые проблемы и хвалиться связями, которых и близко нет
    постоянно говорит, что занят и обещает связаться в ближайшее время, но «в ответ тишина»
    не верьте ему, даже если будет давать расписки и клятвы
    он обещает много, а ничего не делает.

  19. program oversigt:

    Most at ease amelioration initiatives can’t do that. In items, the beadroll of to the spry revolution in compensation the better projects that settle down resale value and debilitate homeowners’ comfy imin.tfulsio.se/tips/program-oversigt.php savings is beyond the innuendo of a host doubts too long. Co-worker quarters constituent (ADU) additions are different. Whether you’re looking to vamp an older domicile or body justice in a brand-new construction home.

  20. RemususVX:

    Это хороший сайт


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


два + = 9