N
N
Nikita Kochnev2017-08-05 15:50:02
JavaScript
Nikita Kochnev, 2017-08-05 15:50:02

How to set up .htaccess correctly for CNC and landingSeo to work simultaneously?

Hello! For the LandingSeo plugin to work correctly, you need to add the following lines to .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,QSA]

The site is on modx revo, and its .htaccess already contains the following code for the CNC to work:
...............
# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
..........

The site is one page. So I didn't notice the problem right away. When replacing the default lines with lines from the plugin, all resources stop working (for example, in my resources: 404, sitemap, robots, etc.). Rather, when you try to go to them, you get to the main page of the site. The plugin is working properly.
If you return the rows to default, then EVERYTHING works, but when you refresh the page, on the section with pseudo-urls, an error 404 is displayed.
What the plugin clings to on the site - an example
<section class="container" id="ourPartners" data-seotitle="Наши партнеры" data-seourl="our-partners.html" data-seodescription="Описание страницы «Наши партнеры»">
    <div class="row">
      <div class="col-md-12">
        <h1>Наши партнеры</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum nesciunt temporibus maiores est itaque odio nimi. Sunt.</p>
        <p>Lorem ipsum vel!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam iusto maiores eaque, tempore animi odio!</p>
      </div>
    </div>
  </section>
Here is the JS of the plugin
(function($) {
  $.landingSeo = function(options) {
    var landingSeo = (function() {
      /*** Переменные ***/
      // Выборки
      var $sel = {};
      // Состояния
      var states = {
        isDefault: false	
      };
      // Параметры
      var settings = {};
      // SEO-параметры по умолчанию
      var seoDefaults = {
        title: '',
        keywords: '',
        description: '',
        url: '/'
      };
      /*** //Переменные ***/
      /*** Вспомогательные функции ***/
      // Получение дефолтных SEO-параметров
      var setSeoDefaults = function() {
        seoDefaults.title = document.title;
        seoDefaults.keywords = $("meta[name=keywords]", getObject("head")).attr("content");
        seoDefaults.description = $("meta[name=description]", getObject("head")).attr("content");
      };
      // Получение положений блоков
      var getBlocksPosition = function() {
        var wh = getObject("window").height();
        getObject("[data-seotitle]").each(function() {
          var $block = $(this),
            blockOffset = $block.offset();
          $block
            .data("top", parseInt(blockOffset.top))
            .data("bottom", parseInt(blockOffset.top + $block.outerHeight()));
        });	
      };
      // Определение текущего активного блока
      var checkBlocks = function(sc, wh) {
        var find = false;
        getObject("[data-seotitle]").each(function() {
          var $block = $(this);
          if(sc >= ($block.data("top") - 80 - settings.offsetTop) && sc <= ($block.data("bottom") + 80 - settings.offsetTop)) {
            if(!$block.data("current")) {
              getObject("[data-seotitle]").data("current", false);
              $block.data("current", true);
              setBlock({
                title: $block.data("seotitle"),
                keywords: $block.data("seokeywords"),
                description: $block.data("seodescription"),
                url: $block.data("seourl")
              });
            }
            find = true;
            states.isDefault = false;
            return false;
          }
        });
        if(!find && !states.isDefault) {
          setBlock(seoDefaults);
          states.isDefault = true;
        }
      };
      // Применение SEO-параметров
      var setBlock = function(params) { console.log(params);
        if(params.title) {
          document.title = params.title;
        }
        if(params.description) {
          $("meta[name=description]").remove();
          $("head").append('<meta name="description" content="' + params.description + '">');
        }
        if(params.keywords) {
          $("meta[name=keywords]").remove();
          $("head").append('<meta name="keywords" content="' + params.keywords + '">');
        }
        if(params.url && window.history.pushState !== undefined) {
          window.history.pushState({}, params.title, params.url);
        }
        // Отправка хита в Яндекс.Метрику
        if(settings.yaCounter) {
          if(window["yaCounter" + settings.yaCounter] !== undefined) {
            window["yaCounter" + settings.yaCounter].hit(params.url, {
              title: params.title
            });
          }
        }
        // Отправка отчета в Google Analytics
        if(window.ga !== undefined) {
          ga("send", {
            hitType: "pageview",
            page: params.url,
            title: params.title
          });
        }
        // Отправка хита в Google Analytics
        if(settings.addGoogleAnalytics && window.ga !== undefined) {
          ga("send", "pageview", window.location.hash);
        }
        settings.onBlockChange();
      };
      // Получение DOM объекта
      function getObject(selector, parent) {
        if(!$sel[selector] || $sel[selector].length == 0) {
          if(!parent) {
            parent = false;
          }
          if(selector == "window") {
            $sel[selector] = $(window);
          } else {
            $sel[selector] = $(selector, $sel[parent]);
          }
        }
        return $sel[selector];
      }
      /*** // ***/
      return {
        getObject: getObject,
        getBlocksPosition: getBlocksPosition,
        checkBlocks: checkBlocks,
        // Инициализация плагина
        init: function(options) {
          settings = $.extend({
            offsetTop: 0, // Отступ сверху
            yaCounter: null, // Код счетчика Яндекс.Метрики
            addGoogleAnalytics: false, // Код GA
            onBlockChange: function() {} // После смены блока
          }, options);
          // Установка SEO параметров
          setSeoDefaults();
          // Получение позиций блоков
          getBlocksPosition();
          // Расположение текущего блока
          checkBlocks(parseInt(getObject("window").scrollTop()), parseInt(getObject("window").height()));
        },
        goToBlock: function(url) {
          getObject("[data-seotitle]").each(function() {
            var $block = $(this);
             if($block.data("seourl") && $block.data("seourl") == url) {
              getObject("window").scrollTop($block.data("top") - settings.offsetTop);
              return false;
            }
          });
        }
      }
    })();
    landingSeo.init(options);
    // Скроллирование к нужному блоку (если содержится в аресной строке)
    landingSeo.goToBlock(window.location.pathname);
    // Получение размеров в начале и при смене размера браузера
    landingSeo.getObject("window").on("resize", function() {
      landingSeo.getBlocksPosition();
    });
    // Проверка блоков при скроллирование и в начале
    landingSeo.getObject("window").on("scroll", function() {
      var sc = parseInt(landingSeo.getObject("window").scrollTop()),
        wh = parseInt(landingSeo.getObject("window").height());
      landingSeo.checkBlocks(sc, wh);
    });
  };
  $.landingSeo(); - вызов. Но у меня вызов сделан иначе - к делу не относится.
})(jQuery);

My site - refresh page starting from achievements.html
Один сплошной косяк
Added to answers!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Viktor Taran, 2017-08-25
@1nks1

do I understand correctly that you have
1 page
and in fact you need a seo module for it
if so, why don’t you clarify your rule with another condom
by limiting the request uri /
in this case they will not conflict
and just throw it into the cnc of the engine exception of this url.

M
McBernar, 2017-08-05
@McBernar

Obviously, MODx sends a GET request to the front controller and processes it with its router. And your plugin wants all requests to go directly to index, without parameters.
Pick routers, perhaps somewhere there is a setting for this parameter. Or you can rewrite.

T
ThunderCat, 2017-08-05
@ThunderCat

hint (perhaps it will help): for different folders, you can register your xtaxes, they will work regardless of the main one (it has priority over the one at the root).

N
Nikita Kochnev, 2017-08-09
@1nks1

Full .htaccess file
# MODX supports Friendly URLs via this .htaccess file. You must serve web
# pages via Apache with mod_rewrite to use this functionality, and you must
# change the file name from ht.access to .htaccess.
#
# Make sure RewriteBase points to the directory where you installed MODX.
# E.g., "/modx" if your installation is in a "modx" subdirectory.
#
# You may choose to make your URLs non-case-sensitive by adding a NC directive
# to your rule: RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,NC]

RewriteEngine On
RewriteBase /

# Rewrite www.domain.com -> domain.com -- used with SEO Strict URLs plugin
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
#
# or for the opposite domain.com -> www.domain.com use the following
# DO NOT USE BOTH
#
#RewriteCond %{HTTP_HOST} !^$
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteCond %{HTTP_HOST} (.+)$
#RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L] .

# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent 
# https://www.domain.com when your cert only allows https://secure.domain.com
#RewriteCond %{SERVER_PORT} !^443
#RewriteRule (.*) https://example-domain-please-change.com/$1 [R=301,L]

<b># The Friendly URLs part
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

#Надстройка LandingSeo
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,QSA]</b>

# Make sure .htc files are served with the proper MIME type, which is critical
# for XP SP2. Un-comment if your host allows htaccess MIME type overrides.

#AddType text/x-component .htc
# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# To verify that this option has been set to OFF, open the Manager and choose
# Reports -> System Info and then click the phpinfo() link. Do a Find on Page
# for "register_globals". The Local Value should be OFF. If the Master Value
# is OFF then you do not need this directive here.
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.
#php_flag register_globals Off
# For servers that support output compression, you should pick up a bit of
# speed by un-commenting the following lines.
php_flag zlib.output_compression On
php_value zlib.output_compression_level 5
# The following directives stop screen flicker in IE on CSS rollovers. If
# needed, un-comment the following rules. When they're in place, you may have
# to do a force-refresh in order to see changes in your designs.
#ExpiresActive On
#ExpiresByType image/gif A2592000
#ExpiresByType image/jpeg A2592000
#ExpiresByType image/png A2592000
#BrowserMatch "MSIE" brokenvary=1
#BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
#BrowserMatch "Opera" !brokenvary
#SetEnvIf brokenvary 1 force-no-vary

List of urls and what they should return
https://helpmyapple56.ru/robots.txt -200 ok
https://helpmyapple56.ru/sitemap.xml -200 ok
https://helpmyapple56.ru/404.html -200 ok

On the site itself, after the page is fully loaded, seotitles, seodescriptons, seourls, etc. are arranged in sections, the problem is that when using the default modx settings, the script works, but when you try to reload the page on one of the sections (for some reason, only except " main page") error 404 falls out.
In theory, all the listed resources, and in general resources in modx, should be generated dynamically through the admin panel, they exist in the database, and when requested, the already generated document is displayed to the client. But at the moment, to solve the problem, I had to completely sacrifice the dynamic resources of the admin panel in favor of static files in the root of the site, the only way I could get them to work. In addition, I had to sacrifice the 404 page, because writing the line
#ErrorDocument 404 helpmyapple56.ru/errors/404.html
in .htaccess - gave nothing. When an error occurs, you get to the main page of the site.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question