DIY CNC machine step by step instructions. CNC milling machine at home (garage)

  • 07.10.2023

I decided to write this note because I’m tired of answering the same thing 100,500 times on Q&A.

Many novice web programmers sooner or later are faced with the task of introducing human-readable links (HUR) into their website. Before the implementation of CNC, all links looked like /myscript.php or even /myfolder/myfolder2/myscript3.php, which is difficult to remember and even worse for SEO. After the implementation of CNC, the links take the form /statiya-o-php or even in Cyrillic /article-o-php.

Speaking of SEO. Human-readable links were REALLY invented not for easy memorization, but mainly to increase the indexability of the site, because the coincidence of the search query and part of the URL gives a good advantage in the search rankings.

The evolution of a novice PHP programmer can be expressed in the following sequence of steps:

  1. Placing plain-PHP code in separate files and accessing these files through links like /myfolder/myscript.php
  2. Understanding that all scripts have a significant part in common (for example, creating a connection to the database, reading the configuration, starting a session, etc.) and, as a consequence, creating a common starting “entry” point, some script that accepts ALL requests, and then chooses which one connect internal script. Usually this script is named index.php and lies at the root, as a result of which all requests (aka URLs) look like this: /index.php?com=myaction&com2=mysubaction
  3. The need to implement a router and the transition to human-readable links.

I note that between points 2 and 3, most programmers make an obvious mistake. I won't be wrong if I call this the value of about 95% of programmers. Even most well-known frameworks contain this error. And it consists in the following.

Instead of implementing a fundamentally new way of processing links, the concept of “patches and redirects” based on .htaccess is mistakenly made, which consists of creating many redirect rules using mod_rewrite. These lines compare the URL with some regular expression and, if there is a match, push the values ​​extracted from the URL into GET variables, subsequently calling the same index.php.

#Incorrect CNC method RewriteEngine On RewriteRule ^\/users\/(.+)$ index.php?module=users&id=$1 #....A lot more similar rules...

This concept has many disadvantages. One of them is the difficulty of creating rules, a large percentage of human errors when adding rules that are difficult to detect, but they lead to a 500 server error.

Another drawback is that it is often edited based on the server config, which in itself is nonsense. And if in Apache the config can be “patched” using .htaccess, then in the popular nginx there is no such option, everything is located in a common configuration file in the system zone.

And one more drawback, probably the most important, is that with this approach it is impossible to dynamically configure the router, that is, “on the fly,” algorithmically change and expand the rules for selecting the desired script.

The method proposed below eliminates all these disadvantages. It is already used in a large number of modern frameworks.

The bottom line is that the initial request is always stored in the $_SERVER[‘REQUEST_URI’] variable, that is, it can be read inside index.php and parsed as a string using PHP with all error handling, dynamic redirects, etc.

In this case, you can create only one static rule in the configuration file, which will redirect all requests to non-existent files or folders to index.php.

RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f #If the file does not exist RewriteCond %(REQUEST_FILENAME) !-d #And if the folder does not exist RewriteRule ^.*$ index.php

Moreover, this rule can be placed both in .htaccess and in the main Apache configuration file.

For nginx, the corresponding rule will look like this:

Location / ( if (!-e $request_filename) ( rewrite ^/(.*)$ /index.php last; ) )

It's simple.

Now let's look at a piece of PHP code in index.php, which analyzes links and decides which script to run.

/part1/part2/part3

The first thing that comes to mind is to break it up using explode(‘/’, $uri) and make a complex router based on switch/case that analyzes each piece of the request. Do not do that! This is complicated and ends up making the code look horribly incomprehensible and non-configurable!

I suggest a more concise way. It’s better not to describe it in words, but to immediately show the code.

"page404.php", // Page 404"/" => "mainpage.php", // Main page "/news" => "newspage.php", // News - page without parameters "/stories(/+)?" => "storypage.php", // With a numeric parameter // More rules); // Router code class uSitemap ( public $title = ""; public $params = null; public $classname = ""; public $data = null; public $request_uri = ""; public $url_info = array(); public $ found = false; function __construct() ( $this->mapClassName(); ) function mapClassName() ( $this->classname = ""; $this->title = ""; $this->params = null; $ map = &$GLOBALS["sitemap"]; $this->request_uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); $this->url_info = parse_url($this->request_uri); $uri = urldecode( $this->url_info["path"]); $data = false; foreach ($map as $term => $dd) ( $match = array(); $i = preg_match("@^".$term. "$@Uu", $uri, $match); if ($i > 0) ( // Get class name and main title part $m = explode(",", $dd); $data = array("classname " => isset($m)?strtolower(trim($m)):"", "title" => isset($m)?trim($m):"", "params" => $match,) ; break; ) ) if ($data === false) ( // 404 if (isset($map["_404"])) ( // Default 404 page $dd = $map["_404"]; $m = explode(",", $dd); $this->classname = strtolower(trim($m)); $this->title = trim($m); $this->params = array(); ) $this->found = false; ) else ( // Found! $this->classname = $data["classname"]; $this->title = $data["title"]; $this->params = $data["params"]; $ this->found = true; ) return $this->classname; ) ) $sm = new uSitemap(); $routed_file = $sm->classname; // Get the name of the file to connect via require() require("app/".$routed_file); // Connect the file // P.S. Inside the included file you can use request parameters // which are stored in the $sm->params property

Even though the code is quite long, it is logically simple. I don't want to explain it, I consider any PHP code to be self-explanatory if it is written correctly. Learn to read code.

Not long ago, I crawled through a fair number of sites, but I couldn’t find anything on the topic that interested me about simple CNC for sites. There were certainly materials, but the story was very unclear and somehow vague, it seemed as if the authors of the texts themselves did not understand what they were writing about. It also resembled a distantly clumsy translation from another language, so clumsy that all meaning was lost.

Well, ever since then I wanted to create my own material about this topic, which would finally reveal the secrets of creating a simple, uncomplicated CNC without frills, strictly and efficiently. We will create CNC using .htaccess and directly mod_rewrite, but everything is in order.

So, let's begin... For example, let's imagine a small situation:

Let's say we need the file index.php took 2 variables, for example cat And art, i.e. index.php?cat=content&art=content. Let within the example cat- category, art- article, and we have material available at index.php?cat=php&art=info-chpu, but we understand how ugly it will look in the address bar of the browser and we need our material to be available at php/info-chpu. Therefore we need CNC:

The main role of the presented CNC is given to the .htaccess file; it does all the work. So what should be in the .htaccess file:

RewriteEngine On

Now I will try to explain the contents of the .htaccess file. Line RewriteEngine On - used to enable redirection, so to speak, according to the rules that you describe. The user follows the link php/info-chpu, the contents of the .htaccess file are launched immediately, which sees that the requested link php/info-chpu matches the rule (.*)/(.*) , which is why it divides the requested address into parts of the rule content1/content2 and transfers them to the executive file index.php?cat=content1&art=content2.

That's all. Now all we have to do is “catch” and use our index.php two variables cat And art.

Attention, if you use cgi-bin as a PHP handler, then instead of a file .htaccess you must have htaccess.txt

Everything is as simple and clear as possible. If you suddenly encounter any difficulties in using the CNC I proposed for the site, I recommend downloading an archive in which everything is configured and working - maybe it will be easier for you to figure it out. There are 3 files in the archive:

index.php- main file

htaccess.txt- file for Cgi-bin handler

.htaccess- file for Apache handler

Unpack the contents of the archive to your server, and try the request for example<ваш_сервер>/trololo/512 or any other,<ваш_сервер>- as you understand, it’s not worth writing, I indicated the place where you will unpack the archive and from where you will run the file.

If you have any questions, write in the comments.

For those who do not understand what and how.

The whole point of this CNC is the htaccess file, but what exactly does it do?

RewriteEngine On
RewriteRule ^(.*)/(.*)$ index.php?cat=$1&art=$2 [L]

We can say that this example takes an address like:

and gives the processors snakes of this type:


And we already accept $_GET["cat"] and $_GET["art"] in the index.php file, which contain the name of the category and material.

The example shown in the article can be modified as desired.

For example, we have a work address domen.ru/avto.php?cat=sportcars&avto=porshe&model=carrera and if we want to make it CNC like:

Then we write in .htaccess:

RewriteEngine On
RewriteRule ^(.*)/(.*)/(.*)$ avto.php?cat=$1&avto=$2&model=$3 [L]

And after we add the above couple of lines to the .htaccess file, our material will open for visitors at the address:

domen.ru/sportcars/porshe/carrera

Or suddenly, if we have several PHP handlers, then we can put a rule in .htaccess for each:

RewriteEngine On
RewriteRule ^avto/(.*)$ avto.php?id=$1 [L]
RewriteRule ^air/(.*)$ forair.php?id=$1 [L]
RewriteRule ^flot/(.*)$ waterflot.php?id=$1 [L]

From the example you can see that all requests starting with domen.ru/avto/ will be sent to the avto.php handler, and all requests starting with domen.ru/air/ will be sent to the forair.php handler.

Now it’s worth noting something important! Before your RewriteRule put this code:

RewriteCond %(REQUEST_FILENAME) !-d
RewriteCond %(REQUEST_FILENAME) !-f

This code will allow you to avoid being directed to a handler when requesting static folders and files physically stored in the site folder.

Another very important feature of CNC, which has not been covered, is links in the HTML code of your site to styles, pictures, etc. The fact is that the relative path to pictures and files that you connect on the page must be compiled taking into account the CNC, since each slash (/) in the address will be treated as a folder. As a result, the relative CNC paths will be of the form "../../". We recommend that you read articles about relative addresses if you do not know how to create their hierarchy in HTML. If you don’t want to bother with this or don’t understand what we’re talking about, just set absolute paths everywhere, that is, for pictures instead of:

src="/images/vasya.png"

src="http://site.com/images/vasya.png"

In this case, the site data will be called correctly at any CNC, with any number of slashes. Do the same with all included files to HTML.

Now is the time to talk about the second option of redirecting via .htaccess. The second option is completely tied to the first, but is a universal redirect from htaccess. A redirect consists of just one rule:

RewriteRule ^(+)$ /engine.php?query=$1 [L]

The whole logic of such a redirect is that absolutely everything after http://site.com/ will be sent to the engine.php handler in the $_GET["query"] variable. Next, in engine.php we can break the variable into parts:

$query=$_GET["query"];

$url=explode("/", $query);

And now we have an array $url which contains part of the full path in each cell. For example, if our address (query variable) looks like this: transport/auto/ferrary/laferrary/description, then after processing it will be:

$url="transport";

$url="auto";

$url="ferrary";

$url="laferrary";

$url="description";

And after processing, you can perform any actions with this data.

And it might be useful: To find out the number of entries in the array, use count($url), to view the value of the last entry in the array, use end($url).

The question of how to make a CNC machine can be answered briefly. Knowing that a homemade CNC milling machine, in general, is a complex device with a complex structure, it is advisable for the designer to:

  • acquire drawings;
  • purchase reliable components and fasteners;
  • prepare a good tool;
  • Have a CNC lathe and drilling machine on hand to produce quickly.

It wouldn’t hurt to watch the video – a kind of instructional guide on where to start. And I’ll start with preparation, buy everything I need, figure out the drawing - this is the right decision for a novice designer. Therefore, the preparatory stage preceding assembly is very important.

Preparatory stage work

To make a homemade CNC milling machine, there are two options:

  1. You take a ready-made running set of parts (specially selected components), from which we assemble the equipment yourself.
  2. Find (make) all the components and start assembling a CNC machine with your own hands that would meet all the requirements.

It is important to decide on the purpose, size and design (how to do without a drawing of a homemade CNC machine), find diagrams for its manufacture, purchase or manufacture some parts that are needed for this, and acquire lead screws.

If you decide to create a CNC machine with your own hands and do without ready-made sets of components and mechanisms, fasteners, you need a diagram assembled according to which the machine will work.

Usually, having found a schematic diagram of the device, they first model all the parts of the machine, prepare technical drawings, and then use them to make components from plywood or aluminum on a lathe and milling machine (sometimes it is necessary to use a drilling machine). Most often, working surfaces (also called a work table) are plywood with a thickness of 18 mm.

Assembly of some important machine components

In the machine that you started assembling with your own hands, you need to provide a number of critical components that ensure the vertical movement of the working tool. In this list:

  • helical gear – rotation is transmitted using a toothed belt. It is good because the pulleys do not slip, evenly transferring forces to the shaft of the milling equipment;
  • if you use a stepper motor (SM) for a mini-machine, it is advisable to take a carriage from a larger printer model - more powerful; old dot matrix printers had fairly powerful electric motors;

  • for a three-coordinate device, you will need three SDs. It’s good if there are 5 control wires in each, the functionality of the mini-machine will increase. It is worth assessing the magnitude of the parameters: supply voltage, winding resistance and motor rotation angle in one step. To connect each stepper motor you need a separate controller;
  • with the help of screws, the rotational movement from the motor is converted into linear. To achieve high accuracy, many consider it necessary to have ball screws (ball screws), but this component is not cheap. When selecting a set of nuts and mounting screws for mounting blocks, choose them with plastic inserts, this reduces friction and eliminates backlash;

  • instead of a stepper motor, you can take a regular electric motor, after a little modification;
  • a vertical axis that allows the tool to move in 3D, covering the entire X-ray table. It is made from aluminum plate. It is important that the dimensions of the axis are adjusted to the dimensions of the device. If you have a muffle furnace, the axle can be cast according to the dimensions of the drawings.

Below is a drawing made in three projections: side view, rear view, and top view.

Maximum attention to the bed

The necessary rigidity of the machine is provided by the bed. A movable portal, a rail guide system, a motor, a working surface, a Z axis and a spindle are installed on it.

For example, one of the creators of a homemade CNC machine made a supporting frame from Maytec aluminum profile - two parts (section 40x80 mm) and two end plates 10 mm thick from the same material, connecting the elements with aluminum corners. The structure is reinforced; inside the frame there is a frame made of smaller profiles in the shape of a square.

The frame is mounted without the use of welded joints (welded seams are poorly able to withstand vibration loads). It is better to use T-nuts as fastenings. The end plates provide for the installation of a bearing block for mounting the lead screw. You will need a plain bearing and a spindle bearing.

The craftsman determined that the main task of the self-made CNC machine was the production of aluminum parts. Since workpieces with a maximum thickness of 60 mm were suitable for him, he made the portal clearance 125 mm (this is the distance from the upper cross beam to the working surface).

This difficult installation process

It is better to assemble homemade CNC machines, after preparing the components, strictly according to the drawing so that they work. The assembly process using lead screws should be performed in the following sequence:

  • a knowledgeable craftsman begins by attaching the first two motors to the body - behind the vertical axis of the equipment. One is responsible for the horizontal movement of the milling head (rail guides), and the second is responsible for movement in the vertical plane;
  • a movable portal moving along the X axis carries the milling spindle and support (z axis). The higher the portal is, the larger the workpiece can be processed. But at a high portal, during processing, the resistance to emerging loads decreases;

  • For fastening the Z-axis motor and linear guides, front, rear, upper, middle and lower plates are used. Make a cradle for the milling spindle there;
  • The drive is assembled from carefully selected nuts and studs. To fix the motor shaft and attach it to the stud, use a rubber winding of a thick electric cable. The fixation may be screws inserted into a nylon sleeve.

Then the assembly of the remaining components and assemblies of the homemade product begins.

We install the electronic filling of the machine

To make a CNC machine with your own hands and operate it, you need to operate with correctly selected numerical control, high-quality printed circuit boards and electronic components (especially if they are Chinese), which will allow you to implement all the functionality on the CNC machine, processing a part of a complex configuration.

In order to avoid management problems, homemade CNC machines have the following components among the components:

  • stepper motors, some stopped for example Nema;
  • LPT port, through which the CNC control unit can be connected to the machine;
  • drivers for controllers, they are installed on a mini-milling machine, connecting in accordance with the diagram;

  • switching boards (controllers);
  • 36V power supply unit with a step-down transformer that converts to 5V to power the control circuit;
  • laptop or PC;
  • button responsible for emergency stop.

Only after this, CNC machines are tested (in this case, the craftsman will make a test run of it, loading all the programs), and existing shortcomings are identified and eliminated.

Instead of a conclusion

As you can see, it is possible to make a CNC that is not inferior to Chinese models. Having made a set of spare parts with the required size, having high-quality bearings and enough fasteners for assembly, this task is within the power of those who are interested in software technology. You won’t have to look for an example for long.

The photo below shows some examples of numerically controlled machines, which were made by the same craftsmen, not professionals. Not a single part was made hastily, with an arbitrary size, but fitted to the block with great precision, with careful alignment of the axes, the use of high-quality lead screws and reliable bearings. The statement is true: as you assemble, so will you work.

A duralumin blank is processed using CNC. With such a machine, which was assembled by a craftsman, you can perform a lot of milling work.

Another example of an assembled machine, where a fiberboard board is used as a work table on which a printed circuit board can be manufactured.

Anyone who starts making the first device will soon move on to other machines. Perhaps he will want to test himself as an assembler of a drilling unit and, unnoticed, will join the army of craftsmen who have assembled many homemade devices. Technical creativity will make people's lives interesting, varied and rich.

The note: The adaptive version of the site is activated, which automatically adapts to the small size of your browser and hides some details of the site for ease of reading. Enjoy watching!

Hello dear guests and regular readers of the blog about website creation - Site on! In one of the previous articles in this section, I promised to tell you how you can create your own CNC links in just a couple of minutes. Despite the fact that the article may seem voluminous to you, and for some, complicated, I hope that when you read it to the end, you will agree that there is really nothing supernatural in creating a CNC.

CNC– this is a distorted English abbreviation (search engines friendly url). It denotes link addresses that are search engine friendly. I also wrote about CNC in an article about. In the Russian version, SEF URL is written as CNC - human-readable url. What does all of this mean? This means that the addresses of your links will have conscious text, and not technical garbage; for an example, you can follow the link above.

What are the benefits of SEF URLs?

Secondly, SEO. Such links are welcomed by search engines; a couple of years ago they could have given you a significant advantage over your competitors. Today, such links are taken for granted; now you rarely see sites with non-CNC links, but they still exist.

Third, this is prestige. When I go to sites where, instead of a clear and beautiful address, the links contain all sorts of garbage, or even classified information, I ask myself the question: “It seems like a decent site, but why didn’t the developers make a CNC? Was it really that difficult? Maybe they just don’t care about such things or just lack knowledge and skills?” In general, such sites are a big mystery to me.

Fourthly, safety. Sites with CNC links do not contain in their address technical information transmitted by the GET () method, which can easily be used to hack the site.

And lastly: CNC – as a means of navigation. If the link is clear to the user, then he can navigate through sections of the site by simply editing your URL. For example:

Http://site/useful/2-sublime-text-2

Http://site/useful/ Options +SymLinksIfOwnerMatch

RewriteEngine On

We have the following .htaccess file:

mod_rewrite terms and conditions

All rules are written using the command RewriteRule, followed by a space and written sample your CNC using regular expressions, then put another space and indicate the line into which we want to convert this template, where $1,$2,...$n are our variables. You can find out more about it at the link above, as well as later in this article. Let's look at an example:

RewriteRule ^useful/(*) /index.php?category=useful&article=$1

Where ^useful/(*)– this is the expected url template,

A /index.php?category=useful&article=$1– this is what we convert it into if the incoming URL matches the template.

Wherein $1 equal to what is written in parentheses, that is $1 = * If the parentheses appeared 2 times, then we would have the variable $1 and $2, if the parentheses appeared 3 times, then the variables $1, $2, $3 and so on. In this case, the variables are created in the same order as the parentheses appear.

It's clear? - Well done. Unclear? - Move on, we’ll come back to this. I would also like to draw your attention to the fact that in order to better understand the article, you should already have basic knowledge of PHP, as well as working with the GET and POST methods. Let's continue.

In order for our handler, that is, mod_rewrite did not work every time unnecessarily, we are in RewriteRule We indicate the template that incoming URLs must match. If the URL doesn't match the pattern, then mod_rewrite simply won't work and won't convert the incoming SEF URL into a URL we can work with.

That is, at this stage it is important for you to understand the very essence: parameters are not passed in CNC links, and without parameters we cannot do anything in PHP with this link, so using mod_rewrite we convert CNC link without parameters V not CNC link with parameters. What are the parameters? In the example above we have 2 parameters:

/index.php?category=useful&article=$1

Parameter category and parameter article.

Again, I would like to draw your attention to the fact that you should already know about the parameters; I only briefly reminded you.

In templates we can use symbols And character classes. The dot symbol represents absolutely any symbol.

  • . – any single character
  • is a character class. Indicates the presence of one of the listed characters, case sensitive.
  • – character class. Indicates the presence of one of the symbols between a before z, that is, the entire English alphabet.
  • - the same thing, only without taking into account the case, that is, the entire alphabet, including both large and small letters.
  • You can also use numbers:
  • Naturally, everything can be combined:
  • [^rewfad]– a character class, but with a ^ sign inside square brackets indicating that the pattern must NOT contain these characters.
  • site|cite– denotes an alternative: site or cite are suitable.

Quantifiers or quantifiers

All previous examples denoted one character (one unit), but what if we want to show that there can be not one, but as many characters from this interval as desired. To do this we must use quantifiers:

  • ? - 0 or 1 character from the previous text (character class, symbol, etc.)
  • * — 0 or any number of characters from the previous text (n>0)
  • + — 1 or any number of characters from the previous text (n>1)
  • (n)— exactly n characters, where n is a specific number.

For example:

  • {4} - must be exactly 4 characters from the previous text.
  • {4,5} — 4 or 5 characters
  • {,6} — from zero to 6 characters
  • {4,} — from 4 to infinity characters

An example is our already famous line:

RewriteRule ^useful/(*)

In which we applied the quantifier (quantifier) ​​asterisk (*) after the character class. This means that in our URL after useful/ There may be symbols from a to z in any number and, naturally, in any sequence, or they may not exist at all. We don’t take the domain into account, it is meant by itself.

Shielding

Also, when creating a template, do not forget about . If you want to enclose, for example, a dot character in a character class, then you need to escape it, since without escaping a dot (service character) means absolutely any character:

The same applies to square brackets, they denote a character class, so if your url may contain square brackets, they need to be escaped:

Start and end of line constraint (markers)

To indicate the beginning or end of a line, regardless of the domain, the following symbols are used:

  • ^ - start of URL
  • $ - end of URL

That is, in our first example, we indicated that our template starts exactly from the beginning of the URL, and not from anywhere (from the middle, from the end):

RewriteRule ^useful/()

Draw your attention Don't be confused by the fact that the ^ sign inside square brackets means negation!

Feedbacks in mod_rewrite

$n– this is our “variable” in parentheses, we have already talked about them. Works for RewriteRule.

%n- the same thing, only in RewriteCond. We haven’t looked at RewriteCond yet, it’s ahead of us.

So if RewriteRule are our URL translation rules, then RewriteCond– this is a condition, an analogue of . RewriteCond is needed in situations where you need to perform a URL transformation (RewriteRule) only when some condition is met.

The server has its own variables that we can use in our RewriteCond conditions:

HTTP headers:
HTTP_USER_AGENT
HTTP_REFERER
HTTP_COOKIE
HTTP_FORWARDED
HTTP_HOST
HTTP_PROXY_CONNECTION
HTTP_ACCEPT REMOTE_ADDR

Connection and request:

REMOTE_HOST
REMOTE_USER
REMOTE_IDENT
REQUEST_METHOD
SCRIPT_FILENAME
PATH_INFO
QUERY_STRING
AUTH_TYPE

Inside the server rooms:

DOCUMENT_ROOT
SERVER_ADMIN
SERVER_NAME
SERVER_ADDR
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

System:

TIME_YEAR
TIME_MON
TIME_DAY
TIME_HOUR
TIME_MIN
TIME_SEC
TIME_WDAY
TIME

Special:

API_VERSION
THE_REQUEST
REQUEST_URI
REQUEST_FILENAME
IS_SUBREQ

The syntax for using server variables is:

%(variable)

Let's create our first condition:

RewriteCond %(HTTP_USER_AGENT) ^Mozilla.* RewriteRule …

If the visitor came from the Mozilla Firefox browser, then we execute the following rule. As you can see, unlike PHP, we do not use curly braces to frame our rule, which will be executed if the condition is TRUE.

RewriteCond allows you to use comparison operators:< (меньше), >(greater than), = (equal). There are also special meanings, for example:

  • -d (is it a directory)
  • -f (is it a file)
  • -s (whether the file is a non-zero size)
  • ! – denial.

Flags

  • nocase|NC– you can write either nocase or NC, this is the same thing, it means case-insensitive. That is, we can no longer write:
RewriteRule ^useful/

Instead write this:

RewriteRule ^useful/

  • ornext|OR– if this or the following condition is TRUE, then we execute RewriteRule. Example:
  • RewriteCond %(REMOTE_HOST) ^host1.* RewriteCond %(REMOTE_HOST) ^host2.* RewriteCond %(REMOTE_HOST) ^host3.* RewriteRule …
  • Last|L- the last rule. If the rule is applied, then the rules located below in the code will not work.
  • next|N– some analogue of continue. If the rule is applied, it forces all the rules to be played from the very beginning, but with the already converted string.
  • redirect|R– redirect. The default is 302. You can specify a different redirect code, for example:
  • forbidden|F– The URL becomes prohibited.
  • gone|G– sends a 410 server response.
  • chain|C-connection. If a rule does not fire, then the rules associated with it will not automatically work either.
  • type|T– MIME type. Forced setting of file type. You can pass off one file extension as another :) For example, we have files with the extension .zip, but in fact they are pictures, so to give these files as pictures (.png, .gif, etc.), you can use this flag .
  • skip|S– skip the next rule, you can specify several at once, for example:
  • env|E=VAR:VAL– set the environment variable.
  • cookie|CO– send cookies.
  • If you need to set several flags at the same time, put them separated by commas, for example:

    As you might have guessed, mod_rewrite can be used not only for CNC, but also for many other interesting purposes, for example, cloaking- This is a black hat SEO method, when one page is given to visitors at the same address, and a completely different one to search robots. Well, at the end of the article, I will show you a live example of using everything written above and how it all works interacting with our PHP.

    Live example of using mod_rewrite

    So, this is what my .htaccess file looks like:

    Options +SymLinksIfOwnerMatch RewriteEngine On
    RewriteCond %(HTTP_HOST) ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1
    RewriteCond %(HTTP_HOST) ^[^www\.].*$ RewriteRule ^/?(+)/?$ /index.php?article=$1 [L]

    What's going on in this horror? To begin with, I check whether the old-school person has typed my address with www; if he has, then I redirect him to the same address, only without www. I will write why exactly this is needed in one of the following articles; in short, for SEO. After redirecting from www to non-www, our .htaccess file was read again, so everything starts again: we check if we received a URL with www, this time - no. Next (second RewriteCond) we check if our URL is indeed without www, then we make transformations, namely: we enter the entire URL (without the domain name) in the article parameter.

    At this point, the work of .htaccess is completed and PHP comes into the picture. The following code is located in index.php:

    If (!empty($_GET["article "]))( // check the article parameter for emptyness switch($_GET["article "])( case "value1": $page = "path to php file1 of our page";break; case "value2": $page = "path to php file2 of our page";break; case "value3": $page = "path to php file3 of our page";break; ... ) include $page; // connect the required file, depending on the received article parameter }

    I wrote in detail about how it works in the article at the link provided. That's it, ladies and gentlemen! Finally, our article has come to its logical conclusion, and now you can practice the knowledge you have acquired. I say goodbye to you before the release of a new article, and finally I want to give you an interesting quote:

    “Despite tons of examples and documentation, mod_rewrite is Voodoo. Damn cool Voodoo, but still Voodoo."

    The world of the Internet is developing rapidly and conquering new heights. Millions of sites, services and services are happy to welcome another user to their pages. A huge number of addresses have been created that are generated automatically. And it’s not always convenient to read and remember them. In addition, a meaningless set of characters ranks poorly in search engines. As a result, it became necessary to introduce the implementation of the code in such a way that it could appear in a more convenient and pleasing form to the user's eye.

    Therefore, in the world of web development, the term CNC links appeared. What this is and how to implement it will be discussed in the article.

    What are CNC links

    In general, CNC is a slang word meaning a human-readable URL. URL - borrowing from the English URL, a uniform resource locator. Human-readable, in turn, means a set of characters in the address bar that is convenient and easy to understand. For example, the generated page address might look like this: http://example.com/index.php?page=name. It doesn’t look very clear and doesn’t show the structure of the site. There are signs that do not carry a semantic load and it is unclear what the page and name mean.

    The following URL might look like this: http://example.com/products/new/boat. It is clear here that we are talking about products, and new ones at that, and specifically about a boat. This is a human-readable URL. It is much better indexed by search engines and is shown in search results above the rest. And a person who visits the site will be able to understand that he has entered exactly the right section.

    However, CNC links have some limitations. For example, Russian characters cannot be used in the address. They are replaced with a numeric value and a percent sign. Therefore, domestic developers use transliteration of Russian words into Latin. For example, so - oborudovanie or produkcia. Also, an automatically generated CNC link can increase the overall length of the line.

    To implement transliteration and conversion to human-readable URLs, special tools are used. They are available, as a rule, in content management systems - CMS. CNC links are created automatically, based on the name of the product, article or blog, as well as the section in which it is posted. As a result, when creating a new record or adding a product, a human-readable URL is formed, which is well perceived by both people and machines.

    How to make CNC links in popular CMS

    CMS is a content management system that, in a convenient and simple interface, allows you to create a full-fledged website in a short time. The functionality is expanded due to the presence of a large number of ready-made templates, modules and plugins. This allows a person who is far from the programming languages ​​PHP, JavaScript, HTML and related ones to quickly create his own website or blog.

    Almost all content management systems have an excellent set of tools in the form of plugins for creating CNC. It is worth taking a closer look at the most common of them.

    • WordPress is the most popular content management system, according to statistics. It is installed on most famous blogs and websites. It is famous for its ease of learning and installation.
    • Joomla is less popular, but is still actively used among developers. It has good functionality, a selection of components, plugins and modules.
    • OpenCart is a separate project for creating online stores. Internally it resembles any CMS, but is “tailored” to solve a narrow range of tasks.

    CNC Links in WordPress - Easy to Implement

    WordPress is probably the simplest content management system out there. It can greatly simplify the creation of a website or blog from scratch in a short time.

    Setting up CNC in WordPress is simple and basically involves downloading and installing the Cyr-To-Lat plugin. It is used to convert Cyrillic strings to Latin.

    First you need to find it and download it. It is better to do this from the official WordPress website. This way you can avoid the possibility of malicious or adware code getting into the plugin.

    • After downloading the archive, you need to unpack it.
    • Then you need to move this folder to the wp-content -> plugins section. This is usually done using any available FTP manager.
    • Now you need to log into the WordPress admin panel by entering your username and password.
    • In the “Plugins” section you need to find Cyr-To-Lat and activate it. The plugin is now installed on the system and enabled.
    • To do this, go to “Options”, and there go to “Permanent Links”.
    • In the general settings there are several templates that you can use to build the appearance of the link. It is recommended to use the “Custom” type, which allows you to configure everything as needed. The simplest design for such a template is /%category%/%postname%/. This means that the category will be displayed in the address bar, followed by the title of the post.
    • And then Cyr-To-Lat converts all this into Latin. As a result, you will get a beautiful and understandable CNC link in WordPress.

    In addition to Cyr-To-Lat, you can also use analogues that are available on the official website. For example, these are WP Translitera, ACF: Rus-To-Lat, Rus-To-Lat Advanced. Installing these plugins is similar, so it makes no sense to dwell on them separately.

    CNC in Joomla, several options for creating

    Joomla is a slightly more complex content management system. Just like WordPress, it has the ability to create websites and blogs in a short time. It has extensive functionality and flexibility. Next, you need to describe how to make CNC links in this CMS.

    Joomla initially has built-in functionality for creating human-readable URLs. CNC links in Joomla 3 can be enabled on the general settings page in the “SEO Settings” section. The item “Enable SEF (CNC)” should be set to “Yes”. This way the links will be converted into a more understandable form.

    Here you can additionally set up URL redirection by creating a CNC link in htaccess. This file acts as a configuration storage for the Apache web server. In it, you can use regular expressions and the RewriteRule directive to change the conversion of the link to the desired URL. The main difference between this approach is flexibility. You can give links to almost any type.

    The “Add suffix to URL” item adds the document extension to the end of the line. For example, html. This extension is of little interest to the average website visitor, so the option can be left in the “No” position.

    Aliases in Unicode - this item transliterates the name of the material into Latin. This is necessary so that instead of Russian letters or other symbols something awkward and unreadable is not displayed.

    Alternative components for Joomla

    You can also implement a CNC link generator in Joomla using various components. For example, one of the popular ones is JoomSEF. It is distributed free of charge and it is better to download it from the official Joomla website.

    Its functionality, in addition to converting URLs into CNC, includes a set for generating metadata, search engines, keywords, as well as managing duplicate pages. It is worth noting the available support for UTF-8 encoding and customization of the 404 page at your discretion.

    There are three installation methods available in Joomla 3: downloading directly from your computer, from the site directory, and by sending a link to it.

    For the first option, you will have to download the file. Then select “Extensions” from the CMS administrative panel menu and go to “Extensions Manager”. Using the “Select file” button, you need to show the system the prepared archive and install it.

    The second option is rarely used. But the third is the most convenient of them, since it does not require downloading. You just need to copy the link to JoomSEF and specify it in the “Install from URL” field on the tab of the same name. The system itself will check for its presence and install it if all parameters match.

    It is worth noting that for the add-on to work fully, the “Enable SEF”, “URL Redirection” and “Add suffix to URL” items in the SEO settings must be set to “Yes”.

    The installed component will immediately be integrated into the system in active mode and begin its work. Namely, it converts all existing links into a more aesthetic appearance.

    JoomSEF has a large number of settings and options. With their help, you can very subtly bring all the site links to almost any necessary form.

    JBZoo and a human-readable URL

    The JBZoo component is a universal and powerful tool for creating online stores, catalogs, blogs and simply business card sites based on the Joomla content management system.

    To install JBZoo in Joomla, it must already have the Zoo add-on.

    Sometimes the standard SEF settings don't reach their components enough to perform the conversion. Therefore, it is recommended to use the sh404SEF component to create CNC links in JBZoo. This product is free and is a good tool for building links in JBZoo. settings, functions, support for various social networks and services.

    Installation is done by copying the link to the archive, or by directly uploading a previously downloaded file to the server.

    OpenCart and CNC setup

    OpenCart is a platform that is not tied to any content management system. That is, it functions separately. Its main focus is the convenient creation of online stores of varying degrees of complexity. Although the product itself is free, many add-ons are distributed on a commercial basis. The latest stable version is 2.0.

    You can start setting up the CNC in the first way by editing the htaccess configuration file of the Apache web server.

    • To do this, you need to go to the site folder via FTP or the file manager available in the administrative memory.
    • The root directory should contain the .htaccess.txt file. Since it has no effect on a system with a txt extension, the first thing to do is rename it to .htaccess. Now the web server will read its directives and execute them.
    • Now you need to go to the site settings and on the “Server” tab enable the use of CNC.
    • All changes must be saved.
    • Now all links should change.

    Sometimes, due to some reasons, many addresses still do not change and remain unclear. To implement this task, you can use the SeoPro component. True, before installing it you will first have to implement OCMOD Multiline Fix. To do this, you need to manually change the code of one file. It is located at admin/controller/extension/modification.php. To edit it, it is recommended to use the Notepad++ utility to avoid problems with encodings.

    You only need to add one line of code to the block after the $limit variable. It looks like this:

    • $quote = $operation->getElementsByTagName("search")->item(0)->getAttribute("quote");
    • if (!$limit) (
    • $limit = -1;

    and after it add:

    • if ($quote == "true") (
    • $search = preg_quote($search);

    Then you need to actually install the SeoPro module itself. The downloaded archive must be unpacked on the server. Then run a couple of database queries using phpmyadmin:

    • ALTER TABLE `oc_product_to_category` ADD `main_category` tinyint(1) NOT NULL DEFAULT "0"; ALTER TABLE `oc_product_to_category` ADD INDEX `main_category` (`main_category`);

    Now we need to edit the main index.php file. The line you are interested in is:

    • $controller->addPreAction(new Action("common/seo_url"));

    which is replaced by:

    • if (!$seo_type = $config->get("config_seo_url_type")) (
    • $seo_type = "seo_url";
    • $controller->addPreAction(new Action("common/" . $seo_type));

    Next, there is a set of procedures related to settings inside the admin panel. In the menu you need to find “Modules”, go to “Modifiers” and click on updates. While here, you need to go to the “Modules” list and install SeoPro in it. Then, by clicking the “Edit” button, go into it and save. After all the manipulations, everything should work; if not, then you need to try reinstalling the module again. Or seek help from specialized forums.

    Implementation of CNC functionality in PHP language

    Most sites on the Internet are written in PHP. It is quite powerful, convenient and easy to learn. Its work is invisible to the user, since the PHP code is processed on the server side and a ready-made HTML page that is understandable to the browser is sent to the browser.

    You can show the implementation of CNC links in PHP using a small code example. However, to bring address lines in real multi-page projects to a human-readable form, you will have to tinker.

    Any website starts its work with the index.php file. It also generates hits to other pages of the site. But first you need to change the htaccess configuration file a little. In it you need to specify or uncomment several directives, as shown in the photo.

    The first line allows you to resolve the URL using the server. The second one sets the base address. The next two lines check for the presence of the file and folder. The latter transfers control to index.php if lines 3 and 4 are implemented without errors.

    To store the correspondence between the page id and its converted value, a table is needed. Therefore it must be created. In particular, you can create a simple one to understand the process. It will contain two fields: SEF and page_id. SEF stores the name and is of type varchar. And page_id are page numbers of type int.

    Now it remains to correct the index.php file itself. This is just an example and in practice for a specific project everything may be slightly different: $result = $_SERVER["REQUEST_URI"]. In this line, the requested URL is transferred to the $result variable.

    • if (preg_match ("/([^a-zA-Z0-9\.\/\-\_\#])/", $result)) ( header("HTTP/1.0 404 Not Found"); echo " Invalid characters in URL"; exit; )

    This block checks for the presence of symbols, numbers and some signs. If there is something other than those listed, then a 404 page is displayed.

    • $array_url = preg_split("/(\/|\..*$)/", $result,-1, PREG_SPLIT_NO_EMPTY);

    An array $array_url is declared here, into which, using the preg_split function, elements that do not have anything extra in the CNC are placed.

    • if (!$array_url) ( $ID_page = 1; )else( $sef_value = $array_url;

    Here the request is processed in the case when the request was made not to a specific page, but to a domain. Therefore, you need to respond with id = 1. Also at this point there is a query to the project database, which finds out whether it has a value from the $sef_value variable in the SEF field. If nothing is found, send the user a 404 page. At the end, the resulting address code is processed and the corresponding materials or elements are returned.

    Pros and cons of using CNC

    The advantages of using human-readable URLs can be listed as follows:

    • the link visually looks more aesthetically pleasing than a set of incomprehensible symbols, especially on unfamiliar sites;
    • remembering the address is much easier;
    • the entire path and structure of the site becomes clear;
    • GET parameters transmitted in the usual way use variables in the address line, which is not the case in the CNC, which means that security is not violated;
    • improving site navigation;
    • SEO optimization improves significantly and search robots index such a site better.

    There are far fewer disadvantages. And the most significant of them is setting. It is not always possible to bring page addresses to a human-understandable form using standard or third-party solutions. Sometimes you have to delve into the code and edit it yourself, which requires knowledge and time. The second drawback is not so significant and concerns sites with high traffic. Due to the formation of links on the fly, the load on the site increases. But since the cost of network equipment is steadily decreasing, few people consider such costs for server resources. In general, the advantages far outweigh the disadvantages, so although human-readable URLs are difficult to implement, they are worth using.

    Conclusion

    The article discusses which links are CNC and which are not. The simplest and fastest solutions to the problem were described in detail. As well as several of the most affordable options for complex approaches. In any case, using a CMS when developing a website significantly reduces labor and time costs when optimizing page addresses. Therefore, a combination of CMS and CNC should be used as the most effective alternative to manual development.