Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Публикация вашего веб-сайта

Эта статья нуждается в редакционном обзоре. Как вы можете помочь.

В процессе перевода.

Как только вы закончите писать код и организовывать файлы, которые составляют ваш веб-сайт, вам нужно расположить все это в Интернете, чтобы люди могли его найти. В этой статье говорится о том как разместить простой пример вашего кода в Интернете без больших трудностей.

Какие существуют варианты?

Публикация веб-сайта это не простая тема, главным образом потому что существует много различных способов сделать это. В этой статье мы не ставим своей целью документировать все возможные методы. Скорее всего, мы обсудим плюсы и минусы трех обширных стратегий с точки зрения новичка, а затем вы пройдете через один метод, который будет работать в настоящее время.

Получение хостинга и доменного имени

Если вы хотите иметь полный контроль над вашем публикуемым веб-сайтом, то вам, вероятно, нужно будет потратить деньги, чтобы купить:

  • Хостинг — арендованное файловое пространство на веб-сервере хостинговой компании. Вы размещаете ваши файлы веб-сайта в этом пространстве, и веб-сервер выдает контент для веб-пользователей, которые запрашивают это.
  • Доменное имя — уникальный адрес по которому люди могут найти ваш веб-сайт, например https://www.mozilla.org, или https://www.bbc.co.uk. Вы арендуете ваше доменное имя на протяжении многих лет у регистратора домена.

Множество профессиональных веб-сайтов располагается в Интернете таким образом.

Дополнительно, вам потребуется FTP-клиент (программа работающая по FTP-протоколу) (более подробно см. Как дорого это стоит: программное обеспечение), чтобы передавать файлы вашего сайта на хостинговый сервер. Существует множество FTP-клиентов, обычно вам нужно войти через клиент на хостинговый сервер используя реквизиты предоставленные вашим хостингом (например: имя пользователя (логин), пароль, имя хоста). Затем FTP-клиент отобразит файлы на вашем компьютере в одной половине окна и файлы на хостинговом сервере в другой половине, так вы сможете перетаскивая копировать файлы с вашего компьютера на сервер и обратно.

Советы по поиску хостингов и доменов

  • Мы не продвигаем какие-то конкретные хостинговые компании здесь. Чтобы найти хостинг и регистратора доменных имен, просто поищите через поисковую систему по запросам "веб-хостинг" и "доменные имена", чтобы найти компании предоставляющие соответствующие сервисы. Во всех таких сервисах вам предоставляется возможность найти себе доменное имя.
  • Ваш домашний или рабочий интернет провайдер может предоставлять хостинговые услуги для небольших веб-сайтов. Набор возможностей в таком случае может быть ограничен, но, тем не менее, он может отлично подойти для ваших первых экспериментов. Попробуйте связаться со своим провайдером и спросить об услуге хостинга.
  • Также есть несколько бесплатных сервисов, таких как Neocities, Blogspot, and Wordpress. Опять же, возможности которые они предоставляют соответствуют цене, но для первых шагов их будет достаточно. Бесплатные сервисы по большей части не требуют FTP-клиентов - вы можете перетаскивать ваши файлы напрямую в веб-интерфейсе.
  • Иногда компании предлагают одновременно и хостинг и домен.

Использование онлайн инструментов, как GitHub или Dropbox

Some tools let you publish your website online:

  • GitHub is a "social coding" site. It allows you to upload code repositories for storage in the Git version control system. You can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your GitHub code, use it, learn from it, and improve on it. You can do that with other people's code too! This is a very important and useful community to get involved in, and Git/GitHub is a very popular version control system — most tech companies now use it in their workflow. GitHub has a very useful feature called GitHub pages, which allows you to expose website code live on the Web.
  • Dropbox is a file storage system that allows you to save your files on the Web and have them available from any computer. Anybody with an Internet connection can access any Dropbox folder that you make publicly accessible. If that folder contains website files, it will be served as a website automatically. See Host websites With Dropbox for more information.

Unlike most hosting, such tools are usually free to use, but you only get a limited feature-set.

Using a web-based IDE such as Thimble

There are a number of web apps that emulate a website development environment, allowing you to enter HTML, CSS and JavaScript and then display the result of that code when rendered as a website — all in one browser tab! Generally speaking these tools are quite easy, great for learning, and free (for basic features), and they host your rendered page at a unique web address. However, the basic features are pretty limited, and the apps usually don't provide hosting space for assets (like images).

Try playing with some of these examples, and see which one you like the best:

Публикация с помощью GitHub

Now let's take you through how to publish your site via GitHub pages. We aren't saying this is the only way or even best way to publish your site, but it is free, fairly simple, and touches upon some new skills that you'll find useful going forward.

Основная настройка

  1. First of all, install Git on your machine. This is the underlying version control system software that GitHub works on top of.
  2. Next, sign up for a GitHub account. It's simple and easy.
  3. Once you've signed up, log in to github.com with your username and password.
  4. Next, you need to create a new repo for your files to go in. Click Plus (+) in the top right of the GitHub homepage, then choose New Repository.
  5. On this page, in the Repository name box, enter username.github.io, where username is your username. So for example, our friend bobsmith would enter bobsmith.github.io.
  6. Click Create repository; this should bring you to the following page:

Загрузка ваших файлов на GitHub

This is where we will have a go at using the command line to put our repository on GitHub. A command line is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface. It will look something like this:

Note: You could also consider using a Git graphical user interface to do the same work, if you feel uncomfortable with the command line.

Every operating system comes with a command line tool:

  • Windows: Command Prompt can be accessed by pressing the Windows key, typing Command Prompt, and choosing it from the list that appears. Note that Windows has its own command conventions differing from Linux and OS X, so the commands below may vary on your machine.
  • OS X: Terminal can be found in Applications > Utilities.
  • Linux: Usually you can pull up a terminal with Ctrl + Alt + T. If that doesn't work, look for Terminal in an app bar or menu.

This may seem a bit scary at first, but don't worry — you'll soon get the hang of the basics. You tell the computer to do something in the terminal by typing in a command and hitting Enter.

  1. Point the command line to your test-site directory (or whatever you called the directory containing your website). For this, use the cd command (i.e. "change directory"). Here's what you'd type if you've put your website in a directory called test-site on your desktop:
    cd Desktop/test-site
  2. When the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository:
    git init
  3. Next, go back to the GitHub site. On the current page, you are interested in the section …or push an existing repository from the command line. You should see two lines of code listed in this section. Copy the whole of the first line, paste it into the command line, and press Enter. The command should look something like this:
    git remote add origin https://github.com/bobsmith/bobsmith.github.io.git
  4. Next, type the following two commands, pressing Enter after each one. These prepare the code for uploading to GitHub, and ask Git to manage these files.
    git add --all
    git commit -m 'adding my files to my repository'
  5. Finally, push the code up to GitHub by going to the GitHub web page you're on and entering into the terminal the second of the two commands we saw in step 3:
    git push -u origin master
  6. Now when you go to your GitHub pages' web address in a new browser tab (username.github.io), you should see your site online! Email it to your friends and show off your mastery.

Note: If you get stuck, the GitHub Pages homepage is also really helpful.

Further GitHub knowledge

If you want to make more changes to your test site and upload those to GitHub, you simply need to make the change to your files just like you did before. Then, you need to enter the following commands (pressing Enter after each one) to push those changes to GitHub:

git add --all
git commit -m 'another commit'
git push

You can replace another commit with a more suitable message to describe what change you just made.

We have barely scratched the surface of Git. To learn more, start off with the GitHub Help site.

Conclusion

By this point, you should have your sample website available at a unique web address. Well done!

Дополнительная литература

Метки документа и участники

 Внесли вклад в эту страницу: bondpuoq, Evgeny_Kurkin
 Обновлялась последний раз: bondpuoq,