Php redirect with out www

Содержание
  1. **EDIT: I finally figured this out. Scroll down for my self-answered self-accepted answer (green check mark) **
  2. 4 Answers 4
  3. How to redirect HTTPS to HTTP and www to non-www URL with .htaccess :
  4. Why .htaccess solution is better:
  5. 301 редирект (переадресация) через .htaccess – на все случаи жизни
  6. Советы
  7. Второй способ сделать редирект – это переадресация через php
  8. Правила переадресаций
  9. 1. 301 редирект с одной страницы на другую
  10. 2. 301 редирект с www на без www (главное зеркало – домен без www)
  11. 3. 301 редирект с без www на www (главное зеркало – домен с www)
  12. 4. 301 редирект со страниц со слешем на без слеша (весь сайт)
  13. 5. 301 редирект со страниц без слеша на слеш (часто в CMS системах устанавливается автоматически)
  14. 6. Один (а не два последовательных!) 301 редирект на без www и с слешем на конце адреса страницы
  15. 7. Один (а не два последовательных!) 301 редирект на c www и со слешем на конце адреса страницы
  16. 8. Один (а не два последовательных!) 301 редирект на c www и без слеша на конце адреса страницы
  17. 9. Один (а не два последовательных!) 301 редирект на без www и без слеша на конце адреса страницы
  18. 10. 301 редирект только адреса site.ru/index.php (без GET параметров) на основное зеркало site.ru
  19. 11. 301 редирект всех адресов с index.php и GET параметрами на страницы только с GET параметрами (вырезать в url index.php)
  20. 12. 301 редирект для index.php, index.html или index.htm (например в Joomla), массовая склейка
  21. 13. 301 редирект url с GET параметрами (динамический URL) на статический
  22. 14. Все страницы одного домена на главную страницу другого домена
  23. 15. Каждая страница одного домена на такой же адрес другого url
  24. 16. Редирект с протокола http на https.
  25. 17. Редирект с протокола https на http.
  26. Может быть полезно:
  27. FAQ

**EDIT: I finally figured this out. Scroll down for my self-answered self-accepted answer (green check mark) **

I’m currently using functions.php to redirect https urls to http for a site which currently has no SSL certificate:

function shapeSpace_check_https() < if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) < return true; >return false; > function bhww_ssl_template_redirect() < if ( shapeSpace_check_https() ) < if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) < wp_redirect( preg_replace( '|^https://|', 'http://', $_SERVER['REQUEST_URI'] ), 301 ); exit(); >else < wp_redirect( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 ); exit(); >> > add_action( 'template_redirect', 'bhww_ssl_template_redirect'); 

In this same function, I’d like to also redirect the www subdomain to non-www. I’ve found a good function here, but need help implementing it into my current function. I’d like to avoid doing this in .htaccess , but would welcome a solution there as well.

Redirecting https to http you need to first have a valid ssl to make the initial handshake and then make the redirect.

W/ the function above I’m able to successfully redirect https to http . Downside is the user still has to pass through a scary browser prompt saying there is no valid ssl certificate. I’m fine with that for now — I’m just struggling with redirecting a www to non via preg_replace() . I need an ‘or’ operator in there somewhere saying ‘https:// | https://www.’

Читайте также:  Syntaxerror invalid character in identifier python

You can try this $url = $_SERVER[‘REQUEST_URI’]; $redirect_url=» $not_allowed = array(‘https://wwww’, ‘https://’); foreach($not_allowed as $types) < if(strpos($url, $types) === 0) < $redirect_url = str_replace($types, 'http://', $url); >>

4 Answers 4

How to redirect HTTPS to HTTP and www to non-www URL with .htaccess :

Note: Although you are redirecting HTTPS to HTTP , I’d recommend doing it the opposite, i.e. HTTP to HTTPS . Better for Security, SEO & Browser compatibility — popular browsers are increasingly making it difficult for HTTP sites.

 RewriteEngine On RewriteCond % =on [OR] RewriteCond % !^example\.com$ RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L] # remaining htaccess mod_rewrite CODE for WordPress 

Why .htaccess solution is better:

It’s better to do these sort of redirects with the web server. From your question, since your web server seems to be Apache , it’s better to do with .htaccess . Why:

  1. It’s faster.
  2. Your functions.php file remains cleaner & does what it’s originally there for, i.e. Theme modifications.
  3. Changing the theme will not affect this.
  4. For every redirect, the entire WordPress codebase doesn’t have to load twice — once before redirect & then after redirect.

Thanks for this. I’ve tried it, but for some reason changes to .htaccess won’t take effect (I’ve tried your way and others). Wondering if I need to restart something to force it to work.

First of all, if you don’t install HTTPS (SSL) properly, then .htaccess rules for HTTPS may not work at all (I’ve written this in my answer already). Also, you must make sure .htaccess is actually working on your site, because if it does, restarting should not be necessary.

Taken from your code I would refactor it like this:

function bhww_ssl_template_redirect() < $redirect_url=''; if ( shapeSpace_check_https() ) < if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) < $url = $_SERVER['REQUEST_URI']; $not_allowed = array('https://www', 'https://'); foreach($not_allowed as $types) < if(strpos($url, $types) === 0) < $redirect_url = str_replace($types, 'http://', $url); >> > else < $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; >$redirect_url = !empty($redirect_url)?$redirect_url:$url; wp_redirect($redirect_url, 301 ); exit(); > > 

Add it the .htaccess rules for the redirect www-> non — www

RewriteEngine On RewriteCond % ^www.yourdomain.com [NC] RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301] 
RewriteEngine On RewriteCond % on RewriteRule (.*) http://%%

But again for this to work you need to have a valid SSL or the «Terror screen» will be shown to users.

Thanks so much for taking the time to do this. Unfortunately the www is not getting removed from the address bar in my case — I don’t think it’s redirecting. I did remove the extra ‘w’ typo from ‘wwww’ in your code, and also tried a version w/ if(strpos($url, $types) !==0) instead of your ===0 because I thought that may be the problem, but couldn’t get it to work. I’ll keep staring at it to see what I can change. If you have any ideas pls let me know.

This is maybe due to the system .htaccess settings. I would try it in private window and look for hidden redirects.

Thx for coming back to this. I’ve tried doing this in .htaccess w/ yours and other methods, but can’t get it to take effect — I think I may need to de-activate and re-activate my wordpress theme to get .htaccess changes to take effect, but I’m not ready to take that step (never done it). So I’ll stick w/ PHP — still can’t get it to work. Your way successfully redirects to https to http, but I still can’t get it to remove the www subdomain. I checked in a private window and didn’t see any hidden redirects in the Network tab (if thats how u check) — just the expected https -> http 301.

Читайте также:  Javascript map remove elements

I did notice after your if else statement you had the if shorthand: $redirect_url = !empty($redirect_url)?$redirect_url:$url; , but $url isn’t defined globally here — its only defined in the if statement. Not sure if that’s a reason or not — maybe $url is globally defined in PHP, or isn’t needed anyways?

@KyleVassella 1) The $url isn’t something should be declared globally as it serves only the local scope for the if statement. It holds the $_SERVER[‘REQUEST_URI’] and should be taken in to account if the $redirect_url stay empty. 2) The .htaccess should work as is without the activation/deactivation of themes. But there is a big if this could change if there is a caching or something else interfering with the rules. I would try to push the rules at the top of the .htaccess .

Источник

301 редирект (переадресация) через .htaccess – на все случаи жизни

301 редирект

Три важных совета и семнадцать конкретных примеров установки 301 переадресации страниц через htaccess!

Советы

Располагайте переадресации страниц в файле от частных к более глобальным (сверху вниз). Например: простая переадресация двух страниц стоит выше, чем глобальное правило редиректов с www на без www. Избегайте последовательных редиректов (двух, трех и т.д.). Правила должны быть настроены так, что при возникновении редиректа он должен перенаправлять пользователя (робота) только один (!) раз. Каждое лишнее переадресация – это секунды драгоценного времени отдачи страницы, это нагрузка на сервер, это нечеткие команды для поисковых роботов. Не забывайте, что многие браузеры кешируют (запоминают редиректы), поэтому проверять переадресации лучше на сайте – http://www.bertal.ru. В файле обязательно должна присутствовать команда:

Второй способ сделать редирект – это переадресация через php

Правила переадресаций

1. 301 редирект с одной страницы на другую

Redirect 301 /test-1/ http://site.ru/test-2/
RewriteCond % ^/test/$ RewriteRule ^.*$ http://site.ru/new-test/? [R=301,L]

2. 301 редирект с www на без www (главное зеркало – домен без www)

RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [L,R=301]

3. 301 редирект с без www на www (главное зеркало – домен с www)

RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301]

4. 301 редирект со страниц со слешем на без слеша (весь сайт)

RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % ![^\/]$ RewriteRule ^(.*)\/$ /$1 [R=301,L]

5. 301 редирект со страниц без слеша на слеш (часто в CMS системах устанавливается автоматически)

RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteRule ^(.*[^\/])$ /$1/ [R=301,L]

6. Один (а не два последовательных!) 301 редирект на без www и с слешем на конце адреса страницы

RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1/ [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % ![^\/]$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://%1/$1/ [L,R=301]

7. Один (а не два последовательных!) 301 редирект на c www и со слешем на конце адреса страницы

RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://www.%1/$1/ [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://www.%1/$1/ [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % ![^\/]$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301]

8. Один (а не два последовательных!) 301 редирект на c www и без слеша на конце адреса страницы

RewriteCond % ^\/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % \/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)\/$ http://www.%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % \/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)\/$ http://www.%1/$1 [L,R=301]

9. Один (а не два последовательных!) 301 редирект на без www и без слеша на конце адреса страницы

RewriteCond % ^\/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % \/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)\/$ http://%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % !\/$ RewriteCond % ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [L,R=301] RewriteCond % !\? RewriteCond % !\& RewriteCond % !\= RewriteCond % !\. RewriteCond % \/$ RewriteCond % ^([^www].*)$ RewriteRule ^(.*)\/$ http://%1/$1 [L,R=301]

10. 301 редирект только адреса site.ru/index.php (без GET параметров) на основное зеркало site.ru

RewriteCond % /index.php RewriteCond % ^\z RewriteRule ^(.*)$ http://site.ru/? [R=301,L]

11. 301 редирект всех адресов с index.php и GET параметрами на страницы только с GET параметрами (вырезать в url index.php)

RewriteCond % /index.php RewriteRule ^(.*)$ http://site.ru/ [R=301,L]

12. 301 редирект для index.php, index.html или index.htm (например в Joomla), массовая склейка

RewriteCond % ^[A-Z]\ /index\.(php|html|htm)\ HTTP/ RewriteRule ^(.*)index\.(php|html|htm)$ http://site.ru/$1 [R=301,L]

13. 301 редирект url с GET параметрами (динамический URL) на статический

RewriteCond % ^id=229 RewriteRule ^.*$ /supermodel/? [R=301,L]
RewriteCond % /test/ RewriteCond % ^id=229 RewriteRule ^.*$ /supermodel/? [R=301,L]

14. Все страницы одного домена на главную страницу другого домена

RewriteCond % (.*) RewriteRule ^(.*)$ http://site.ru/ [L,R=301]

15. Каждая страница одного домена на такой же адрес другого url

RewriteCond % (.*) RewriteRule ^(.*)$ http://site.ru/$1 [L,R=301]

16. Редирект с протокола http на https.

RewriteCond % !=on RewriteRule ^(.*)$ https://%/$1 [R=301,L]
RewriteCond % off RewriteCond % !https RewriteRule ^(.*)$ https://%% [L,R=301]
RewriteCond % !^443$ RewriteRule .* https://%% [R,L]
RewriteCond % '"scheme":"http"' # Without Cloudflare: # RewriteCond % off RewriteRule ^ https://www.example.com% [NE,R=301,L]

17. Редирект с протокола https на http.

RewriteCond % =on RewriteRule ^(.*)$ http://%/$1 [R=301,L]

Может быть полезно:

FAQ

Проверять в браузере опасно, т.к. они часто кешируют ответ. Лучше всего воспользоваться Яндекс.Вебмастером или bertal.ru.

Читайте также:  first-letter

Обратиться в поддержку хостинга, где расположен ваш сайт, возможно, у вас отключен файл .htaccess или какая-то не самая стандартная конфигурация сервера.

Источник

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