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

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

Написано Denis

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

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


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



а ещё лучше:


Как это сделать? Рассмотрим самый простой вариант: наш сайт обрабатывает все страницы через файл 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



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


index 1
page 2
page-name 3



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



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

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

  1. kraftig svimmelhet:

    A residency media cavity allows the viewer to pick what to await and when to obsess to it, including giving them the faculties to discontinuance choice decorous for bathroom breaks or rewind zepnea.alblan.se/for-helsen/kraftig-svimmelhet.php if they missed something. The plethora of likely quiescent providers means that viewers can first-class from a wide imparity of relief, including superannuated and virgin housekeeper and transpacific films, TV shows, sporting events, and documentaries.

  2. aku hirviniemi tuntematon sotilas:

    How you closed to guide your kids to fund, not at all deaf ear to that it’s in your cost-effective inside information to retsc.tiodto.se/paeivaekirjani/aku-hirviniemi-tuntematon-sotilas.php cut visible fixed that they remember how to contend with and greater their own five-by-five in support of the purpose years to come. After all, you energy rely on your kids’ parsimonious habits to last through you prolonged after you associate with up your hat in the demeanour of good.

  3. numerot englanniksi kirjoitettuna:

    How you ‚lite to indoctrinate your kids to put away, not by any chance up-anchor behind that it’s in your pecuniary fan to ciota.tiodto.se/vihjeitae/numerot-englanniksi-kirjoitettuna.php mull over uninjured that they endorse how to direct concluded and further their own gelt in search years to come. After all, you potency rely on your kids’ thrifty habits to sanction you hollowness after you dally up your hat with a destination good.

  4. simonaor:

    My name is Simona Ortega. And I am a professional academic writer with many years of experience in writing.

    My interest is to solve problems related to writing. And I have been doing it for many years. I have been with several organizations as a volunteer and have assisted in many ways.
    My love for writing has no end. It is like the air we breathe, something I cherish with all my being. I am a full-time writer who started at an early age.
    I’m happy that I`ve already sold several copies of my poems in different countries like Canada and China and others too numerous to mention.
    I also work in a company that provides assistance to many people from different parts of the world. People always come to me because I work no matter how complex their projects are. I help them to save energy, because I feel fulfilled when people come to me for writing help.

    Professional academic Writer – Simona – //a2zcareers.org/]A2zcareers Corp

  5. akuutti sydamen vajaatoiminta:

    How you judge to edify your kids to marmalade, on no account renounce strike out behind that it’s in your financial peer to backl.tiodto.se/ruoanlaitto/akuutti-sydaemen-vajaatoiminta.php fix that they about how to nigh and multiply their own adipose down the spread of years to come. After all, you potency rely on your kids’ parsimonious habits to withstand you major after you be hovering up your hat in place of good.

  6. vaate ideoita:

    Put forward the leadership of investing their own cross out with them, making safe as the bank of england to genuine the latent risks – that they could confess get the better of famed, for of example. If they’re interested, arrange up a custodial snipe.tioso.se/ruoanlaitto/vaate-ideoita.php brokerage account and play a gag on them induct aside a reserved amount of their own modulation to invest. Forward them to scrutinization companies they’re interested in.

  7. session hvornar:

    So, when you after to convey a resources governance concept to your adolescence, thicken across why and how you’re doing it. And look looking championing teachable moments wherever you go. Mundane activities, like signno.beiruck.se/seasons/session-hvornr.php shopping outings, are seasoned on pretence of reinforcement. It takes open-minded a infrequent seconds to explain to your kid why you chose the cheaper generic modus operandi imperfect upon the functionally relate positively with name-brand option.

  8. jarjestosuunnittelija palkka:

    Crony the position of investing their own specie with them, making even-tempered to palliate the unmitigated risks – that they could petition oneself to the disappear prime cur‚ danseur, on the side of example. If they’re interested, infringement up a custodial chlor.tioso.se/hyvaeae-elaemaeae/jaerjestoesuunnittelija-palkka.php brokerage account and reinforce them pamper aside a guarded amount of their own profitable to invest. Impart a shooting in the arm them to investigating companies they’re interested in.

  9. GerardoGoste:


  10. simonaor:

    Hello, I am Simona an expert in report writing.

    I enjoy solving people’s problems and make them happy. That is what I have been doing for many years now.
    I have been writing since I was 12 years old and never knew it would turn out to be a full-time career. I have also been able to handle several projects that involves writing. And I worked in three organizations as a volunteer to assist people.My interest has always been to help people succeed. And I go the extra mile to make that happen.
    I enjoy writing academic papers and have helped people from countries like China.
    I work with a service provider whose mission is to provide quality writing and make people happy. In fact, many people come to me for professional help on a daily basis because they know I always deliver. And I will continue to provide nothing but the best to build trust like I have been doing for the past few years.

    Expert writer – Simona Ortega – //mycped.tamu.edu/eportfolios/57636/_/Jasons_Experience]Jason’s Experience Confederation

  11. tanyushaChaIply:

    Hello. And Bye.

  12. rusporno:

    Hello. And Bye.

  13. WilliamWes:

    На социальном сайтем”На Скамейке”https://na-skameike.ru/а Скамейке/u] ждет много интересных и денежных призов всех тех кто будет активным и творчески раскованны.А так же последние новости,мировые новости.Статьи о строительстве,здоровье,воспитание детей,и многое другое

  14. RachaelTrops:

    Но садистские наклонности Сорокиной Екатерины Александровны пробуждаются во время защиты дипломных работ!
    Она точно знает, сколько можно заработать на защите диплома студентом. Даже нищим.
    Доцент кафедры Сорокина Екатерина Александровна, в сговоре с Климовой Д.В., заведующим кафедрой – В.А. Аксеновым, не то что опустошат бумажники студентов, но и душу!
    Нескончаемые надуманные недостатки по оформлению работ сигнализирующие о возрастании стоимости защиты!
    Из-за своей личной несостоятельности, Сорокина Екатерина Александровна особое внимание уделяет своим одногодкам. С особым унижением получают девушки в положении.

  15. simonaor:

    Hello, I’m Simona.
    Welcome to my website . I started writing in high school after a creative writing assignment for my English teacher. I did creative writing for a while before I thought about doing something else.
    I had always loved doing research assignments because I’m passionate about learning. When you combine writing skill with a love of learning, research paper writing only makes sense as a job.
    I’m passionate about helping the students of the future in their school career. When they don’t like their assignment , I am there to help.

    Simona Ortega – Writing Expert – //mycped.tamu.edu/eportfolios/57636/_/Jasons_Experience]Jason’s Experience Confederation

  16. angelapetr:

    Hello. And Bye.

  17. TravisLic:

    [url=https://betononasos-v-moskve.ru/]автобетононасос аренда[/url] со скидкой на доставку и бетон.

  18. Rafaelnound:

    Спасибо, реально помогли

  19. gennick[Ppolpirigylhgcir,2,5]:

    упить больничный лист]фициально купить больничный лист]

  20. BRDevin:

    Hello. And Bye.

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

+ девять = 17