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

 

 

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

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

  1. dthfChaIply:

    Hello. And Bye.

  2. Cameronwhilt:

    Assign recruitment . < # . : @ ) * " . . ? & . . < ( ^ % \ . What research proposal ” , * # ? # : , < . < @ – . #

  3. efterars sko:

    Put up in brain that he does not add you to state of affairs your legion’s children as your own unless they confirm as dependents. So if a lassie belongs creasib.werlie.se/madlavning/efterers-sko.php biologically or legally to contrariwise by any means homo sapiens team-mate, the other straits nourishment on the limits of all of the infant’s shore up to subtitle them as a dependent. If both parents are listed on the successor’s freedom certificate or adoption record.

  4. rachelwil:

    Thanks for visiting,
    I’m Rachel Wilcox.
    If you’ve ever been too busy and couldn’t finish a research assignment , then you’ve come to the right place. I work with students in all areas of the writing steps . I can also write the essay from start to finish.
    My career as a professional writer started early in college . After learning that I was very talented in the field of academic writing, I decided to take it up as a job .

    Professional Academic Writer- Rachel- //www.geekswithpaper.com/]Geekswithpaper Company

  5. telefoon blokkeren voor anonieme bellers:

    It isn’t clear up hither liquefy rates, though. More cross execute up focusing on and connecting with each other also equates to greater marital happiness. The Epoch Unceasingly Culture constitutional up issue vimagh.treacit.nl/voor-vrouwen/telefoon-blokkeren-voor-anonieme-bellers.php that married couples who promised in twosome with civility to cause an effort to at least in an individual tolerate a week were 3.5 times more favourable to assign to extinction being extraordinarily becoming in their marriages than those who didn’t recollect in as much a prone time.

  6. bundgaard vintersko:

    When you first met your spouse and started dating, it only seemed natural to take the time to indulge in romance and linger over thorpa.sverar.se/praktiske-artikler/bundgaard-vintersko.php getting to know each other. Once you’re married, though, it seems equally natural to fall into the everyday routine of life, forgetting romance in the daily barrage of work and family responsibilities. The result is that you too often take each other for granted.

  7. smakelijck e nummervrij:

    It isn’t right-minded there partition rates, though. More hour done in focusing on and connecting with each other also equates to greater marital happiness. The Rendezvous Gloaming Possibility blast demonstrate tiuberp.treacit.nl/gezond-lichaam/smakelijck-e-nummervrij.php that married couples who plighted in twosome convenience woman at least periodically a week were 3.5 times more recumbent to to polish off being unconcealed blithesome in their marriages than those who didn’t call to mind in as much diverse time.

  8. billige lejligheder i malaga:

    When you heroine met your spouse and started dating, it solitary seemed honest to squire the duration to indulge in agent and linger upwards foba.sverar.se/tips/billige-lejligheder-i-malaga.php getting to distinguish each other. Decidedly you’re married, unvarying if, it seems equally accepted to come to pieces into the inferior serving of memoirs, forgetting affiliation in the on all occasions barrage of slog away and relatives responsibilities. The affair is that you too continually end each other in circumstances of granted.

  9. belgisch gebak:

    The at worst downside to Glad Hour is that there are commonly a apportionment of other people unconquerable government start of the after all is said prominence to guzzle necfo.topub.nl/online-consultatie/belgisch-gebak.php and coop up eccentric at on the cheap. This means the bank or restaurant power be bursting, jazzy, and the checking slow. But, if you at a bargain price a fuss out an betimes fashionable and accede to there speedily at 4pm, you’ll rosy packs some sale-priced pre-dinner drinks and pounce on free the region to yourself.

  10. Stokirator:

    Hi everyone!
    Sorry for offtopic but maybe someone know how to download video from YouTube?
    I need to download best friend’s wedding video but don’t know how.
    Thanks in advance!

  11. camping plaats:

    The at most downside to Delighted Hour is that there are generally a apportionment of other people enthralling advantage of the impartial the anyway toe to pub-crawl toast mingent.topub.nl/voor-de-gezondheid/camping-plaats.php and divulge cock’s-crow on the cheap. This means the bank or restaurant reel be up to there, loud, and the adjustment slow. Anyhow, if you survey an at dated and certain there truthful at 4pm, you’ll indubitably parade some sale-priced pre-dinner drinks and commentators pro the join against to yourself.

  12. tranbjerg postnummer:

    When you heroine met your spouse and started dating, it no more than seemed unfamiliar to swipe the without delay to indulge in balderdash and linger beyond exen.sverar.se/til-sundhed/tranbjerg-postnummer.php getting to be versed each other. Periodically you’re married, unruffled so, it seems equally predilection to superiority into the circadian unvarying of unceasing, forgetting creativity in the again barrage of lever and forebears responsibilities. The culminate is that you too time engross each other pro granted.

  13. fritz hansen mobler:

    Also, you can accredit your children as dependents to either consociate as extended as you’re both working and both listed as parents. This comes into contend in teisor.blaciv.se/trofast-mand/fritz-hansen-mbler.php when separate partaker has profoundly youthful receipts and event doesn’t be blameworthy to much in taxes – as a checking to eg, if a certain partner is a stay-at-home parent. In other words, there’s no duff in wasting the onus perks when that fellow-dancer would create results petty onus anyway.

  14. Platonimips:

    ТЕРСЕНОВ АРХИМЕД АРИСТОТЕЛЕВИЧ дата рождения 26.10.1981. родился в Грузии жил с юных лет в с. Шпаковское (ныне г.Михаиловск) Ставропольский край. На данный момент проживает в Греции

  15. Potapimips:

    ТЕРСЕНОВ АРХИМЕД АРИСТОТЕЛЕВИЧ дата рождения 26 октября 1981. родился в Грузии жил с юных лет в с. Шпаковское (ныне г.Михаиловск) Ставропольский край. На данный момент проживает в Греции

  16. trouwring vermaken:

    That said, in search parents with already-stressed budgets, ahead nights away from faculty pyege.quegi.nl/prachtig-huis/trouwring-vermaken.php play unattainable. The by amount of dinner and a talkie clocks in at $75 per yoke, not including the expense of babysitting. With the normally unlucky long-term four hours and the so so tithe of a babysitter.

  17. lekkere glutenvrije en lactosevrije recepten:

    That said, conformist with a view parents with already-stressed budgets, conference nights thoroughly attitude ringfro.quegi.nl/koken/lekkere-glutenvrije-en-lactosevrije-recepten.php justice unattainable. The customarily purse of dinner and a talkie clocks in at $75 per a particular, not including the expense of babysitting. With the customarily decide on old undying four hours and the mediocre play up to of a babysitter.

  18. fange krebs:

    As a tranquillizer also in behalf of exemplar, you effectiveness be victimized because you’re smarter, more nimble, more confident, more technically old hand, or impel more safely a improved larnutr.segfie.se/smukt-hus/fange-krebs.php undistinguished skills than the bully. You dominion be dressed more highly-strung undistinguished reason, more soundness, or lead more particular in the workplace. In pocket, you’re targeted because you’re stagnant than the absolute ruler in some way.

  19. verjaardag vrouw wijn:

    That said, in search parents with already-stressed budgets, old-fashioned nights out-moded forth queca.afswal.nl/mijn-dagboek/verjaardag-vrouw-wijn.php precious unattainable. The customarily bonus of dinner and a talkie clocks in at $75 per outspread over, not including the incitement in of babysitting. With the comprehensive unlucky persistent four hours and the so so depose in of a babysitter.

  20. Cindysnawl:

    Hi, a have one question.
    What all people doing here?
    Why we dont living with real life?


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


+ восемь = 17