@1dzanami

Почему не срабатывает 404 ошибка?

Добрый день.
Настраиваю .htaccess
И не срабатывает перенаправление на 404.html
Подскажите почему так.
#Options +Includes +FollowSymLinks -Indexes
#DirectoryIndex index.php index.html

ErrorDocument 404 /404.html


AddDefaultCharset windows-1251

<ifModule mod_headers.c>
  <filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|svg|woff|ttf|JPG)$">
    Header set Cache-Control "max-age=31536000, public"
  </filesMatch>
  <filesMatch "\.(css)$">
    Header set Cache-Control "max-age=31536000, public"
  </filesMatch>
  <filesMatch "\.(js)$">
    Header set Cache-Control "max-age=31536000, private"
  </filesMatch>
  <filesMatch "\.(xml|txt)$">
    Header set Cache-Control "max-age=216000, public, must-revalidate"
  </filesMatch>
  <filesMatch "\.(html|htm|php)$">
    Header set Cache-Control "max-age=1, private, must-revalidate"
  </filesMatch>
</ifModule>

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/css
  <IfModule mod_setenvif.c>
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  </IfModule>
</IfModule>

<ifModule mod_expires.c>
	ExpiresActive On
	
	#по умолчанию кеш в 5 секунд
	ExpiresDefault "access plus 5 seconds"
	
	#кэшировать флэш и изображения на месяц
	ExpiresByType image/x-icon "access plus 2592000 seconds"
	ExpiresByType image/jpeg "access plus 2592000 seconds"
	ExpiresByType image/png "access plus 2592000 seconds"
	ExpiresByType image/gif "access plus 2592000 seconds"
	ExpiresByType image/svg+xml "access plus 2592000 seconds"
	ExpiresByType application/font-woff "access plus 2592000 seconds"
	ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
	
	#кэшировать css, javascript и текстовые файлы на одну неделю
	ExpiresByType text/css "access plus 2628000 seconds"
	ExpiresByType text/javascript "access plus 2628000 seconds"
	ExpiresByType application/javascript "access plus 604800 seconds"
	ExpiresByType application/x-javascript "access plus 604800 seconds"
	
	#кэшировать html и htm файлы на один день
	ExpiresByType text/html "access plus 43200 seconds"
	
	#кэшировать xml файлы на десять минут
	ExpiresByType application/xhtml+xml "access plus 600 seconds"
</ifModule>

<IfModule mod_gzip.c>
	mod_gzip_on         Yes
	mod_gzip_dechunk    Yes
	mod_gzip_item_include file		\.(html?|txt|css|js|php|pl|png)$
	mod_gzip_item_include mime		^text\.*
	mod_gzip_item_include mime		^application/x-javascript.*
	mod_gzip_item_exclude mime		^image\.*
	mod_gzip_item_exclude rspheader	^Content-Encoding:.*gzip.*
</IfModule>

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?/ru/$1 [QSA,L]
RewriteCond %{HTTP_HOST} ^www.astgr.ru$ [NC]
RewriteRule ^(.*)$ http://astgr.ru$1 [R=301,L]
RewriteCond %{HTTP_HOST} (.*)
RewriteCond %{REQUEST_URI} /$ [NC]
RewriteRule ^(.*)(/)$ $1 [L,R=301]


Есть предположение, что всё из-за строчек
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?/ru/$1 [QSA,L]

Которые говорят ссылаться на index.php
Но не могу понять что в нем изменить, что бы заработало.
<?php

if ($_SERVER['REQUEST_URI'] == '/index.php') {
    header("HTTP/1.0 301 Moved Permanently");
    header ("Location: /\n\n");
    exit;
}

if ($_SERVER["HTTP_HOST"] == "s4.novelsite1.ru" && $_SERVER['REQUEST_URI'] == '/') {
    header("HTTP/1.0 301 Moved Permanently");
    header ("Location: http://astgr.ru/\n\n");
    exit;
}
elseif ($_SERVER["HTTP_HOST"] == "s4.novelsite1.ru" && $_SERVER['REQUEST_URI'] != '/') {
    header("HTTP/1.0 301 Moved Permanently");
    header ("Location: http://astgr.ru".$_SERVER['REQUEST_URI']."\n\n");
    exit;
}


require('./inc/site.inc');

$qs = to_html($qs);
$content = '';
$static_page = false;

    if ($act == '') {
        // первая страница
        if ($global_level == 0) {
            if (sizeof($http_file_values)) {
                if ($http_file_values[0] == 'news') {
                    $content = news_show($http_file_values);
                }
            }
            else {
                $content = category_show($current_category, 'first_page.tpl');
            }
        }
        // вторые страницы
        elseif ($global_level >= 1) {
            if (sizeof($http_file_values)) {
                if ($http_file_values[0] == 'news') {
                    $content = news_show($http_file_values);
                }
                elseif ($http_file_values[0] == 'product') {
                    $content = product_show($http_file_values);
                }
                else {
                    if ((integer)$http_file_values[0] > 0) {
                        // просмотр документа
                        $content = document_show($http_file_values);
                        statistic_doc_add((integer)$http_file_values[0]);
                    }
                    else {
                        header("HTTP/1.0 404 Not Found");
                        echo file_get_contents($GLOBALS['site_dir'].'404.html');
                        exit;
                    }
                }
            }
            else {
                $content = category_show($current_category);
            }
        }
    }
    // страница рез-тов поиска
    elseif ($act == 'search') {
        require_once ($site_dir.'inc/search.inc');
        $current_category['navy_array'][] = array('title' => $lang_searchres, 'navy_tag' => '/'.$lang.'/search', 'type' => 0);
        $content = search_site($qs);
    }
    else {
        header("HTTP/1.0 404 Not Found");
        echo file_get_contents($GLOBALS['site_dir'].'404.html');
        exit;
    }

    chdir($site_dir);
    $smarty->caching = false;

    $smarty->assign('CONTENT', $content);

    if ($current_category['tag'] == 'yml' || $current_category['tag'] == 'sitemap.xml') {
        header('Content-Type: text/html; charset=utf-8');
        header('Content-type: application/xml');
        header("Last-Modified: ".date("D, d M Y H:i:s")." GMT");
        eval('$direct_content =  '.$current_category["user_function"].'('.$current_category["user_function_params"].');');
        print(mb_convert_encoding($direct_content, 'UTF-8', 'CP1251'));
        //print($direct_content);
        exit;
    }

    if ($prn == 0) {
        if (isset($current_category['layout']) && $current_category['layout'] != '') {
            $smarty->assign('current_category', $GLOBALS['current_category']);
            $smarty->display($current_category['layout']);
        }
        else {
            $smarty->display('layout.tpl');
        }
    }
    elseif ($prn == -1) {
        echo $direct_content;
    }
    else {
        $smarty->display('layout_print.tpl');
    }
  • Вопрос задан
  • 195 просмотров
Пригласить эксперта
Ответы на вопрос 2
Compolomus
@Compolomus
Комполом-быдлокодер
Попробуйте не просто кинуть заголовок 404
https://www.php.net/manual/ru/function.http-respon...
Ответ написан
Комментировать
shambler81
@shambler81 Куратор тега htaccess
В вашем фйайле очень мало не ошибочного кода.
1. google page speed требует кеша максимального
2. болшее количество расширений файлов
3. у вас редирект
RewriteCond %{REQUEST_URI} /$ [NC]
RewriteRule ^(.*)(/)$ $1 [L,R=301]
не учитывает множенство нужных вещей
не говоря что идет преобразование урлов после чпу, что уже совсем ни в какие ворота, притом еще по маске .*
4. Кто использует столь старую мазилу? тем более она обновляется автоматически??? давайте еще netscape navigator будем поддерживать?

############################################################################
RewriteEngine On
   #  Директива включает редиректы.
RewriteBase / 
   # Без директивы (.*) = /$1 будет /var/wwww/site/web/$1  с директивой  = /$1
Options +FollowSymLinks
   # Разрешает переход по символическим ссылкам.
ErrorDocument 404 /404.html
   # 404 
AddDefaultCharset windows-1251
   # реально в 19 году 1251 кто-то использует?

############################################################################
#### Выбор основного зеркала (с www или без www)                        ####
############################################################################
    # 1. Удалить www
RewriteCond %{ENV:HTTPS} on
    #Если включен https
RewriteRule .* - [E=SSL:s]
    #То создаем переменную  ssl с текстом s
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    # Проверяем, содержит ли домен www в начале URL.
RewriteRule ^(.*)$ http%{ENV:SSL}://%1/$1 [R=301,L]
    # Перенаправляем удаляем www

    # 2. Добавить www
#RewriteCond %{ENV:HTTPS} on
    #Если включен https
#RewriteRule .* - [E=SSL:s]
    #То создаем переменную  ssl с текстом s
#RewriteCond %{HTTP_HOST} !^www\.(.*) [NC]
    # Если нет www в начале домена
#RewriteRule ^(.*)$ http%{ENV:SSL}://www.%{HTTP_HOST}/$1 [R=301,L]
    #Подставляем www и https если он включен.

############################################################################
#### Перенаправляем протокол https на http                              ####
############################################################################
#RewriteCond %{HTTPS} on
   # Проверяем наличие https в URL.
#RewriteRule ^.*$ http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
   # Перенаправляем протокол на http.

############################################################################
#### Перенаправляем протокол http на https                              ####
############################################################################
RewriteCond %{HTTPS} off
   # Проверяем наличие https в URL.
RewriteCond %{REQUEST_URI} !^/bitrix/admin/1c_exchange\.php$ [NC] 
   #  Исключим обмен с 1С, ему требуется только 200 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
   # Перенаправляем протокол на http.

############################################################################
#### Убираем index.php, если он есть в конце URL                        ####
############################################################################
RewriteCond %{REQUEST_URI} ^(.*)/index\.php$
   # URL cодержит index.php в конце.
RewriteCond %{REQUEST_METHOD} =GET
   # Выявляем GET запрос в URL (не POST).
RewriteRule ^(.*)$ %1/ [R=301,L]
   # Удалить index.php из URL.
############################################################################
#### Убираем повторяющиеся слеши (/) в URL                              ####
############################################################################
RewriteCond %{THE_REQUEST} //
   # Проверяем, повторяется ли слеш (//) более двух раз.
RewriteCond %{QUERY_STRING} !http(s|)://
  # Убедимся что это не урл в  GET
RewriteRule .* /$0 [R=301,L]
   # Исключаем все лишние слеши.

############################################################################
#### Убираем слеши в конце URL для статических файлов (содержит точку)  ####
############################################################################
RewriteCond %{REQUEST_URI} \..+$
   # Если файл содержит точку.
RewriteCond %{REQUEST_FILENAME} !-d
   # И это не директория.
RewriteCond %{REQUEST_FILENAME} -f
   # Является файлом.
RewriteCond %{REQUEST_URI} ^(.+)/$
   # И в конце URL есть слеш.
RewriteRule ^(.+)/$ /$1 [R=301,L]
   # Исключить слеш.

############################################################################
#### Добавляем слеш(/), если его нет, и это не файл.                    ####
############################################################################
RewriteCond %{REQUEST_URI} !(.*)/$
   # Если слеша в конце нет.
RewriteCond %{REQUEST_FILENAME} !-f
   # Не является файлом.
RewriteCond %{REQUEST_URI} !\..+$
   # В URL нет точки (файл).
RewriteCond %{REQUEST_URI} ^(.+)$
 # В URL есть хоть один символы
RewriteRule ^(.*)$ $1/ [L,R=301]
   # Добавляем слеш в конце.


############################################################################
#### Компрессия статического контента для гугл  спид тест               ####
############################################################################
<IfModule mod_deflate.c>
  AddType image/svg+xml .svg
  AddOutputFilterByType DEFLATE image/svg+xml  
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>
<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/svg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType text/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
  ExpiresByType application/x-font-ttf "access plus 1 year"
  ExpiresByType application/x-font-opentype "access plus 1 year"
  ExpiresByType application/x-font-woff "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
</IfModule>
  <IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|webp|png|gif|css|swf|svg|woff|pdf)$">
    Header set Cache-Control "max-age=31536000, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
    Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
    Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js|otf|ttf|woff|woff2)$">
    Header set Cache-Control "max-age=31536000, private"
  </filesmatch>
  </IfModule>
############################################################################
#### Конец общей части, далее следует собственные директивы .htaccess   ####
############################################################################


<IfModule mod_gzip.c>
  mod_gzip_on         Yes
  mod_gzip_dechunk    Yes
  mod_gzip_item_include file		\.(html?|txt|css|js|php|pl|png)$
  mod_gzip_item_include mime		^text\.*
  mod_gzip_item_include mime		^application/x-javascript.*
  mod_gzip_item_exclude mime		^image\.*
  mod_gzip_item_exclude rspheader	^Content-Encoding:.*gzip.*
</IfModule>

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?/ru/$1 [QSA,L]
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Искра Екатеринбург
от 80 000 до 100 000 ₽
Art gorka Санкт-Петербург
от 60 000 ₽
25 апр. 2024, в 11:20
1000 руб./за проект
25 апр. 2024, в 11:02
5000 руб./за проект
25 апр. 2024, в 10:42
150000 руб./за проект