Action home index module php

На сервере LAMP я хочу, чтобы URL-адрес http://example.com/index.php был переписан на http://example.com. Как я могу это сделать?

Мой текущий файл .htaccess выглядит следующим образом .

IndexIgnore * ErrorDocument 400 /index.php?module=error&action=error ErrorDocument 401 /index.php?module=error&action=error ErrorDocument 403 /index.php?module=error&action=error ErrorDocument 404 /index.php?module=error&action=error ErrorDocument 500 /index.php?module=error&action=error RedirectMatch 301 ^/media/$ / RedirectMatch 301 ^/media/documents/$ / RedirectMatch 301 ^/media/graphics/$ / RedirectMatch 301 ^/media/photos/$ / RedirectMatch 301 ^/library/$ / RedirectMatch 301 ^/library/css/$ / RedirectMatch 301 ^/library/ht/$ / RedirectMatch 301 ^/library/js/$ / RedirectMatch 301 ^/library/php/$ / RewriteEngine on RewriteBase / RewriteRule ^home$ /index.php?module=home&action=frontpage RewriteRule ^home/$ /index.php?module=home&action=frontpage RewriteRule ^home/([^/\.]+)$ /index.php?module=home&action=$1 RewriteRule ^home/([^/\.]+)/$ /index.php?module=home&action=$1 RewriteRule ^cv$ /index.php?module=home&action=cv RewriteRule ^cv/$ /index.php?module=home&action=cv RewriteRule ^release$ /index.php?module=release&action=release RewriteRule ^release/$ /index.php?module=release&action=release RewriteRule ^photos$ /index.php?module=gallery&action=album&album=general RewriteRule ^photos/$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery/$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery/([^/\.]+)$ /index.php?module=gallery&action=album&album=$1 RewriteRule ^gallery/([^/\.]+)/$ /index.php?module=gallery&action=album&album=$1 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)$ /index.php?module=gallery&action=album&album=$1$&page=$2 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/$ /index.php?module=gallery&action=album&album=$1$&page=$2 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/([^/\.]+)$ /index.php?module=gallery&action=item&album=$1$&page=$2&item=$3 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/([^/\.]+)/$ /index.php?module=gallery&action=item&album=$1$&page=$2&page=$3 RewriteRule ^handouts$ /index.php?module=home&action=handouts RewriteRule ^handouts/$ /index.php?module=home&action=handouts RewriteRule ^links$ /index.php?module=home&action=links RewriteRule ^links/$ /index.php?module=home&action=links RewriteRule ^contact$ /index.php?module=home&action=contact RewriteRule ^contact/$ /index.php?module=home&action=contact RewriteRule ^login$ /index.php?module=authentication&action=login RewriteRule ^login/$ /index.php?module=authentication&action=login RewriteRule ^logout$ /index.php?module=authentication&action=logout RewriteRule ^logout/$ /index.php?module=authentication&action=logout RewriteRule ^copyright$ /index.php?module=home&action=copyright RewriteRule ^copyright/$ /index.php?module=home&action=copyright RewriteRule ^error$ /index.php?module=error&action=error RewriteRule ^error/$ /index.php?module=error&action=error 

Как мне отредактировать мой файл .htaccess, чтобы выполнить эту базовую перезапись? Кроме того, мы будем очень благодарны за любые другие отзывы относительно моего кода .htaccess.

Я никогда в жизни не видел такого пушистого файла .htaccess. Вы действительно написали всю эту ерунду и не знаете, как добавить это простое правило перезаписи?

Читайте также:  Php print post get

Я написал это, лол, но у меня проблемы с ошибкой цикла перенаправления. Возможно, он слишком густой! lol Есть рекомендации, как сделать код более эффективным?

1 ответ

Но это не имеет смысла, поскольку / , скорее всего, послужит index.php . Если в вашем каталоге есть файл index.php и вы не хотите использовать его по умолчанию, это очень странная конфигурация! но возможно, конечно . если вы указали разные DirectoryIndex в конфигурации вашего веб-сервера.

Возможно, вы хотите перенаправить index.php на / .

В этом случае вы можете поместить RedirectMatch в свою конфигурацию, например RedirectMatch 301 ^/index.php$ / , но я бы рекомендовал сделать это в вашем php-файле, прямо глядя на ваш $_SERVER[«REQUEST_URI]; , но это вопрос стиля. Мне лично нравится иметь как можно больше контроля в моем приложении, если это возможно, и переходить к конфигурации сервера только в том случае, если это быстрее или необходимо .

После вашего комментария, который прояснил, что вам действительно нужно, я могу дать вам два решения.

Redirect / RedirectMatch не будет работать, потому что вы не можете сделать это условно, где вы можете проверить действительный URI запроса. Кроме того, окончательно обслуженный URL будет использоваться для сопоставления перенаправления. что означает ПОСЛЕ перенаправления на index.php через apache через директиву DirectoryIndex . поэтому эти методы не смогут отличить / от /index.php .

Поэтому вам нужно сделать это либо в своем файле php, который

Посмотрите, заканчивается ли $_SERVER[‘REQUEST_URI’] на index.php , это произойдет только в том случае, если он действительно запрошен (введен в строку браузера). там вы можете сделать перерисовку, используя header(«Location: . «) .

Используя mod rewrite , который также может выполнять переадресацию и может делать это при определенных условиях. включил имеющуюся у вас конфигурацию ( DirectoryIndex ) для демонстрационных целей. На самом деле вам нужны только строки RewriteCond и RewriteRule .

DirectoryIndex index.php RewriteEngine On RewriteBase / RewriteCond % ^[A-Z]\ /index\.php\ HTTP/ RewriteRule ^index\.php$ http://www.yourdomain.com/ [R=301,L] 

Я не уверен, можно ли покинуть свой домен и просто набрать / , вы можете найти это. это будет только в том случае, если URL-адрес запроса на самом деле /index.php , применит rewriterule, которое выполняет перенаправление.

Я думаю, что вы правы в том, что я ищу перенаправление с index.php на / Однако использование RedirectMatch 301 ^ / index.php $ / вызывает ошибку загрузки страницы цикла перенаправления. Любые идеи?

Я использовал версию 2, и она отлично работает. Большое спасибо! Следует отметить, что (1) строка DirectoryIndex index.php не кажется необходимой и (2) замена yourdomain.com с просто / кажется, работает.

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

Источник

How to create php class for navigation action

Can someone tell me how to create php class to for navigation action, I would like to write url like this on browser suppose if I want home page then http://myserver.mydomain.com/index/home then action will be home function index.php. I know i can achieve this using $_POST and $_GET , but I want to try something like how codeigniter works like that so far I tried like this

 function home() < include('test/header.php'); include('test/home.php'); include('test/footer.php'); >function about() < include('test/header.php'); include('test/about.php'); include('test/footer.php'); >> ?> 

Why not rewrite the URL with .htaccess, and use _GET to load the specific controllers/models/view for a specific «page». It would be much better as you wouldn’t have to add another function for each page — but only the logic (model/controller/view — should you choose the MVC approach)

You cant call parent::__construct() if you dont have a parent class! What you are looking for is a router script, such as github.com/dannyvankooten/AltoRouter

I did not suggest to use codeigniter, I commented the link to show you how codeigniter does it, that’s what you are asking for: but I want to try something like how codeigniter works like.

1 Answer 1

Assume we have the following rewrite rule;

RewriteEngine On RewriteRule ^([^/]*)$ /index.php?module=$1 [L,QSA] 

This will rewrite a request like; http://example.php/index.php?module=about to http://example.php/about

Now, let’s see how the Router is done;

 public function setModule($strModuleName) < $this->strModule = $strModuleName; > public function loadModule() < if( file_exists('modules/'. $this->strModule .'.php') ) < include 'modules/'. $this->strModule .'.php'; > else < 'modules/404.php'; >> > 

Now, let’s use the router in index.php

$objRouter = new Router(); $objRouter->setModule($_GET['module']); $objRouter->loadModule(); 

And our tree will be like;

 - index.php - modules/ - about.php - 404.php 

Of course, this is just a quick job, and it can be improved a lot.

Note: The pretty urls (.htaccess rewrite rules) are just for eye-candy. You can achieve this by not using rewrite rules, even with the same code supplied above

Источник

Is there a more efficient way to code this .htaccess file?

Is there a more efficient way to code the .htaccess file I have included below? Also, is the order of all the different elements ok? One user described the file as the «bushiest» htaccess he had ever seen, so I want to learn how I can make it better. Thanks in advance!

 AuthName "Restricted Area" AuthType Basic AuthUserFile /web/example.com/library/ht/.htpasswd AuthGroupFile /dev/null require valid-user IndexIgnore * ErrorDocument 400 /index.php?module=error&action=error ErrorDocument 401 /index.php?module=error&action=error ErrorDocument 403 /index.php?module=error&action=error ErrorDocument 404 /index.php?module=error&action=error ErrorDocument 500 /index.php?module=error&action=error RedirectMatch 301 ^/media/$ / RedirectMatch 301 ^/media/documents/$ / RedirectMatch 301 ^/media/graphics/$ / RedirectMatch 301 ^/media/photos/$ / RedirectMatch 301 ^/library/$ / RedirectMatch 301 ^/library/css/$ / RedirectMatch 301 ^/library/ht/$ / RedirectMatch 301 ^/library/js/$ / RedirectMatch 301 ^/library/php/$ / RewriteEngine on RewriteBase / RewriteCond % ^[A-Z]\ /index\.php\ HTTP/ RewriteRule ^index\.php$ / [R=301,L] RewriteRule ^home$ /index.php?module=home&action=frontpage RewriteRule ^home/$ /index.php?module=home&action=frontpage RewriteRule ^home/([^/\.]+)$ /index.php?module=home&action=$1 RewriteRule ^home/([^/\.]+)/$ /index.php?module=home&action=$1 RewriteRule ^cv$ /index.php?module=home&action=cv RewriteRule ^cv/$ /index.php?module=home&action=cv RewriteRule ^release$ /index.php?module=release&action=release RewriteRule ^release/$ /index.php?module=release&action=release RewriteRule ^photos$ /index.php?module=gallery&action=album&album=general RewriteRule ^photos/$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery/$ /index.php?module=gallery&action=album&album=general RewriteRule ^gallery/([^/\.]+)$ /index.php?module=gallery&action=album&album=$1 RewriteRule ^gallery/([^/\.]+)/$ /index.php?module=gallery&action=album&album=$1 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)$ /index.php?module=gallery&action=album&album=$1$&page=$2 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/$ /index.php?module=gallery&action=album&album=$1$&page=$2 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/([^/\.]+)$ /index.php?module=gallery&action=item&album=$1$&page=$2&item=$3 RewriteRule ^gallery/([^/\.]+)/([^/\.]+)/([^/\.]+)/$ /index.php?module=gallery&action=item&album=$1$&page=$2&page=$3 RewriteRule ^handouts$ /index.php?module=home&action=handouts RewriteRule ^handouts/$ /index.php?module=home&action=handouts RewriteRule ^links$ /index.php?module=home&action=links RewriteRule ^links/$ /index.php?module=home&action=links RewriteRule ^contact$ /index.php?module=home&action=contact RewriteRule ^contact/$ /index.php?module=home&action=contact RewriteRule ^login$ /index.php?module=authentication&action=login RewriteRule ^login/$ /index.php?module=authentication&action=login RewriteRule ^logout$ /index.php?module=authentication&action=logout RewriteRule ^logout/$ /index.php?module=authentication&action=logout RewriteRule ^copyright$ /index.php?module=home&action=copyright RewriteRule ^copyright/$ /index.php?module=home&action=copyright RewriteRule ^error$ /index.php?module=error&action=error RewriteRule ^error/$ /index.php?module=error&action=error 

Источник

Оцените статью