网站/WordPress从虚拟主机搬家到VPS上

拖了一个月终于着手并且完成了。其实没有什么难的。但是因为我对Linux的了解非常局限,还是花了一番功夫,同时学了很多东西,在这里记一下。没有试图写一篇“手把手教你搬WP”,只是记录一些我觉得有帮助的东西,希望做同样的事情的且同样不是那么牛逼的Linux学习者们有用:)

虽说是WordPress搬家,但是任何一个小型网站搬家都差不多这样了吧,嘿嘿。

如果用cPanel和MySQLAdmin之类的东西可能就很傻瓜,但是第一cPanel太贵了(竟然要425多刀一年,我都笑了),第二VPS都买了必须必须要抓住每一个学Linux的机会啊。

过程如下(断断续续弄了好几天…):

环境

虚拟主机和VPS都是host2ez的,最牛逼的主机提供商。系统是CentOS Linux 5.6,apache(现在改名叫httpd)已经装好了,再装

yum php mysql mysql-server

就成。

文件

这个简单,cPanel把虚拟主机上文件打包,VPS上wget下来就好。WP的独立性做的好,文件路径改变不会有什么问题。备份用的插件BackUpWordpress倒因为出问题了,不能识别路径,我直接禁用掉了,VPS嘛马上弄个备份方案还不容易,不需要用WP的插件了。在[wordpress path]/wp_config.php里把信息改一下,数据库部分的怎么改见下面。

数据库

对数据库命令不了解的同学建议先看一下mysql的教程。我不能把所有操作都写出来…这次弄这个还学了不少数据库的东西…tutorial很容易搜到,我觉得有一个比较好的命令列表点 这里,里面包括了所有常用的命令。

在虚拟主机的cPanel – mysqladmin里备份出.sql文件,传上VPS,导入文件的命令是

mysql – u user_name -p database_name < file_name.sql

很多地方写的-p后面跟密码,我用的版本-p后面不跟东西,回车以后才提示输密码,可能是新版本不提倡显式输入密码了吧。非要用的话就–password=”xxxxxx”

如果你导出文件选的是整个mysql,需要打开文件把database”information_schema”部分删掉,否则会失败,这个db貌似是mysql自己的,不能改..不懂

之后要建立一个用户并给此用户分配使用相应db的权限,虽然我们也可以直接把root用户写进wp_config.php但是稍微有点安全意识的程序员都不会想要这么做的…虽然权限没什么大不了的,但是名字叫root就是不行! 所以进数据库:

mysql -u root -p

进去以后添加用户:

mysql> create user 'username'@'localhost' identified by 'mypass';

分配权限:

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

然后就把这个用户甩给Wordpress啦(编辑wp_config.php)

测试的时候有一些问题

上面完了就能http进vps的ip看到博客了,但是不要去点任何东西…因为数据库里“本站”的地址还是原来的域名,这样如果你原来的网站还开着那么随便点个链接就进到原来网站了,如果没开那就can’t find page啦。

而且因为没法进后台改,所以只好进mysql改了

mysql> use viaxlcom_viaxlcom;
mysql> select * from wp_options where option_value rlike "^http";
+-----------+---------+-------------+----------------------------+----------+
| option_id | blog_id | option_name | option_value               | autoload |
+-----------+---------+-------------+----------------------------+----------+
|         2 |       0 | siteurl     | http://axlarts.com/blog      | yes      |
|        39 |       0 | home        | http://axlarts.com           | yes      |
|        41 |       0 | ping_sites  | http://rpc.pingomatic.com/ | yes      | 
+-----------+---------+-------------+----------------------------+----------+
3 rows in set (0.06 sec)
update wp_options set option_value="http://12.34.56.78/blog" where option_id=2;
update wp_options set option_value="http://12.34.56.78" where option_id=39;

这样就把VPS上的网站地址改成本身的IP了。

————————————-
另外我发现一些插件会出现权限问题,比如JW player(放flv视频用的插件),没法启用插件因为提示不能写目录,我整个www目录都是755权限,设置成777以后可以开启了,然后再弄回来。这个问题解决了但是原因一直不知道,直到我因为另一个问题搜了一下才搞明白。

另一个问题是:更新插件update的时候会提示我输入ftp帐号,以前没这事啊,于是我就去装了个vsftpd(ftp的服务端),设置好能更新了,但是为什么?后来搜到这篇文章 <Auto Update WordPress Without FTP> 解决了ftp的问题并且意识到上面的问题也和这个有关系,即因为目录的owner不是httpd,所以网站脚本没有对文件操作的权限。

/var/www目录的owner要设置成httpd的运行者(可以用ps aux或者top命令查看),可能是www,apache或者nobody或者其他的。我的是apache,所以在chown apache:apache /var/www -R之后update就不用输ftp了,我立刻关了vsftpd依然ok,可见之前是绕了弯子了,没权限还用ftp操作文件…

绑域名

进godaddy面板直接改A地址就好了,没有别的要操作的。

但是因为我本来虚拟主机上就放了两个网站,所以怎么在一个VPS上绑定多个域名多个网站?之前用cPanel是傻瓜操作,没有怎么弄?这个我也弄了好半天最终解决了,马上再写一篇单独说吧

好啦好啦,到此结束,路人有问题可以在下面留言~

6,229 thoughts on “网站/WordPress从虚拟主机搬家到VPS上

  1. syvenirnaya prodykciya s logotipom_pyol

    Срочно нужен совет тем, кто занимается брендингом. Хотим обновить мерч для сотрудников. Везде говорят про индивидуальный подход, но реально где заказать корпоративные подарки с логотипом компании — чтоб не за границей, но и не откровенный шлак. купить сувенирную продукцию с логотипом https://suvenirnaya-produkcziya-s-logotipom-9.ru Кто недавно заморачивался подарками с логотипом, поделитесь контактами. Пока просто собираем инфу. Заранее спасибо, кто откликнется.

    Reply
  2. LarryMib

    Solid value for anyone willing to read carefully, and a look at explorefuturepathwaysnow extends that value across the rest of the site, this is the kind of place that rewards return visits rather than offering everything in a single splashy post and then leaving readers nothing to come back for later which is unfortunately common.

    Reply
  3. 1xbet giris_urPt

    Deneyip de begenen cok oldu. Girdim c?kt?m derken zaman kaybettim. En sonunda guvenilir bir kaynak buldum.

    Bu isin puf noktalar? var. Su an en h?zl? cal?san 1xbet giris adresi tam olarak soyle: 1xbet türkiye 1xbet türkiye. Herkesin bildigi gibi — 1xbet turkiye icin tek adres buras?.

    Sorunsuz baglant? icin bu link yeterli. Kendi deneyimim buysa da — arayuz zaten al?s?k oldugunuz gibi. Gonul rahatl?g?yla girebilirsiniz…

    Reply
  4. 1xbet giris_vgPt

    Arkadaslar uzun suredir ar?yordum. Girdim c?kt?m derken zaman kaybettim. En sonunda dogru adrese ulast?m.

    Spor bahisleriyle ilgilenenler bilir. Su an en h?zl? cal?san 1xbet giris adresi tam olarak soyle: 1xbet yeni giriş 1xbet yeni giriş. Yani k?sacas? — 1xbet guncel adres arayanlar buraya baks?n.

    Denemek isteyen kac?rmas?n. Kendi deneyimim buysa da — cekim konusunda s?k?nt? yasamad?m. Gonul rahatl?g?yla girebilirsiniz…

    Reply
  5. shkola onlain_wloi

    Я в шоке от количества предложений в последнее время, но после кучи долгих обсуждений наткнулся на один рабочий и проверенный вариант. К слову, вот что я понял: современная школа онлайн — это серьёзный и комплексный подход. Там и программа насыщенная, без лишней воды, так что прогресс виден сразу.

    В общем, кому реально нужно нормальное обучение в теме онлайн образование школа — убедитесь во всём сами, вот здесь все выложено без лишней воды: школа дистанционное обучение школа дистанционное обучение.

    Если честно, даже не ожидал такого крутого качества. Потому что стандартный дистант бывает дико скучным для ребенка, а тут организована именно живое регулярное общение с кураторами. Держите этот вариант у себя в закладках.

    Reply
  6. syvenirnaya prodykciya s logotipom_nemr

    Коллеги, всем привет! Срочно нужна консультация тех, кто уже заказывал мерч для бизнеса. Подскажите, где заказать качественную сувенирную продукцию с логотипом. сувениры с логотипом на заказ сувениры с логотипом на заказ А то насчитали мне за брендированные блокноты космос, хотя заказывали всего 50 позиций. Бюджет пока не утвержден, поэтому хочу понять рыночные цены. А то маркетинговые агентства такой ценник лупят — закачаешься.

    Reply
  7. EmilianoFah

    Skipped the social share buttons but might come back to actually use one later, and a stop at growththroughclarity extended that share urge, content that triggers genuine sharing impulses rather than performative ones is content that has actually moved me and not many posts in a typical week do that for me actually.

    Reply
  8. HermanTom

    Refreshing to read something where the words actually mean something instead of filling space, and a stop at focusdrivesresults kept that going, the writing here trusts the reader to follow along without endless repetition or constant reminders of what was already said earlier in the post which I appreciate.

    Reply
  9. melbet_wget

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

    Reply
  10. CharlieAcili

    Well done, the writing is professional without being stiff, and the topic is treated with care, and a look at learnandscaleideas reflected that approach, the kind of site I would point a colleague to if they asked for a reliable starting point on this topic in the future without any hesitation at all.

    Reply
  11. Louisshush

    Came back to this an hour later to reread a specific section, and a quick visit to findgrowthchannelsfast also drew a second look, content that pulls you back rather than letting you move on permanently is the kind I want to fill my browser bookmarks with in 2026 and beyond as the open internet evolves.

    Reply
  12. syvenirnaya prodykciya s logotipom_hzSl

    Народ, привет! Директор увидел бюджет и чуть инфаркт не схватил, надо вписаться в сумму. Может, кто шарит где лучше брать сувенирную продукцию с логотипом. сувениры с логотипом сувениры с логотипом Говорят, сейчас модно заказывать корпоративные подарки сувениры из экокожи — но кто делает качественно. Просили ещё брендированные кружки и толстовки. Заранее респект тем, кто откликнется с контактами проверенными.

    Reply
  13. ReeseGuets

    Reading this on a long flight and finding it the best thing I read across hours of trying, and a stop at explorefreshdirectionalideas kept the streak going, when content beats long flight reading you know it has substance because flight reading is a hard test of a piece given the alternatives available everywhere.

    Reply
  14. MicahStoff

    Thanks for sharing this with the open internet rather than locking it behind a paywall like so many sites do now, and a stop at startthinkingstrategicallynow kept the same vibe going, generous helpful and clearly written by someone who actually wants people to learn from it rather than just charge them.

    Reply
  15. BrockBab

    Bookmarked the page and the homepage too because clearly there is more to explore here, and a quick stop at learnandadvancepathnow only made that more obvious, this is the kind of place I want to dig through over a weekend rather than rushing through during a coffee break tomorrow morning before getting back to work.

    Reply
  16. syvenirnaya prodykciya s logotipom_lqmr

    Коллеги, всем привет! Встала задача обновить ассортимент брендированной атрибуки для отдела продаж. Посоветуйте нормальное изготовление корпоративных сувениров — чтобы и кружки не облазили, и ручки писали. бизнес сувениры бизнес сувениры Реально ли найти недорогую сувенирную продукцию с логотипом с печатью от 100 штук. Бюджет пока не утвержден, поэтому хочу понять рыночные цены. А то маркетинговые агентства такой ценник лупят — закачаешься.

    Reply
  17. vivod iz zapoya v stacionare_musr

    Народ, приветствую. Дело деликатное, но решил черкануть пару строк, потому что в экстренной ситуации трудно сориентироваться. Когда нужен проверенный и опытный врач для капельницы, то не рискуйте и не доверяйте случайным объявлениям.

    Знакомые вызывали бригаду в похожей ситуации чтобы помощь оказали без лишних хлопот и в спокойной атмосфере. Чтобы узнать точные цены и вызвать специалиста, вся информация есть здесь: запой санкт петербург запой санкт петербург.

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

    Reply
  18. Sebastianjef

    Grateful for posts like this one, they remind me there are still places online run by people who care about quality, and a look at startsmartdirection reflected the same standards, you can tell the difference between content made for readers and content made just for search engines today and this is the former.

    Reply
  19. ColbyAbify

    Honestly enjoyed not being sold anything for the entire duration of the post, and a look at learnandacceleratesuccess kept that pleasant absence going across more pages, content that exists for its own sake rather than as a funnel to a paid product is increasingly rare and worth supporting where I can find it.

    Reply
  20. JaylenShage

    Decided not to skim despite my usual habit and was rewarded for the discipline, and a stop at designyourdirection earned the same patient approach, training myself to recognise sites that warrant slower reading is part of being a careful online reader and this site is the kind that helps me practice that skill regularly.

    Reply
  21. syvenirnaya prodykciya s logotipom_pgSl

    Народ, привет! Директор увидел бюджет и чуть инфаркт не схватил, надо вписаться в сумму. Ищу нормальное изготовление корпоративных сувениров с доставкой по Москве. подарки клиентам с логотипом компании https://suvenirnaya-produkcziya-s-logotipom-10.ru А то эти менеджеры по рекламе такие цены выкатывают — волосы дыбом. Просили ещё брендированные кружки и толстовки. А то я уже второй день в интернете сижу и ничего адекватного не нашёл.

    Reply
  22. Ianmup

    Now understanding why someone recommended this site to me a while back, and a stop at discoverinnovativethinking explained the recommendation, sometimes recommendations make sense only after experience and this site has finally clicked into place as the kind of resource I now understand was being recommended for sound editorial reasons by my friend.

    Reply
  23. tkan dlya mebeli_bjkn

    Ребята, выручайте! Купил кресло б/у, каркас норм, но ткань в ужасном состоянии. Ищу, где можно ткань для обивки мебели купить не по космическим ценам. обивочная ткань для мебели купить обивочная ткань для мебели купить Интересно про ткань для обивки мебели — какой вариант самый практичный для дивана, где постоянно лежат с чипсами. Буду благодарен за любые советы, особенно от тех, кто сам перетягивал.

    Reply
  24. shkola onlain_baoi

    Я в шоке от количества программ в интернете в последнее время, но после изучения реальных отзывов наткнулся на один нормальный человеческий вариант. Короче, вот что я понял: современная школа онлайн — это не просто унылые вебинарчики. Там и домашние задания с подробной индивидуальной проверкой, так что прогресс виден сразу.

    В общем, кому понимает толк в теме образовательные онлайн школы — посмотрите условия, вот здесь все разжевано до мелочей: онлайн-школа для детей онлайн-школа для детей.

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

    Reply
  25. HermanTom

    Generally I do not leave comments but this post merits a small note, and a stop at focusdrivesresults extended that comment worthy quality, the urge to actively contribute to a sites community rather than passively consume from it is something specific content provokes and this site has provoked that engagement urge from me today.

    Reply
  26. melbet_fdet

    Давно искал инфу и наконец-то нашел нормальный разбор темы. Там всё разложено по полочкам, без лишней воды и тупых SEO-текстов. Многие на форумах спорят, а ответ лежал на поверхности. Вот скачать мелбет на андроид скачать мелбет на андроид — сохраняйте себе в закладки, пригодится. Мне лично это сэкономило кучу времени и нервов, так что делюсь от души.

    Reply
  27. syvenirnaya prodykciya s logotipom_ujmr

    Коллеги, всем привет! Встала задача обновить ассортимент брендированной атрибуки для отдела продаж. Интересует надежный поставщик корпоративных подарков с логотипом компании, который не подведет со сроками. корпоративные подарки клиентам с логотипом корпоративные подарки клиентам с логотипом А то насчитали мне за брендированные блокноты космос, хотя заказывали всего 50 позиций. Может, есть проверенные фабрики, которые работают напрямую, без посредников. А то маркетинговые агентства такой ценник лупят — закачаешься.

    Reply
  28. syvenirnaya prodykciya s logotipom_dtmr

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

    Reply
  29. Louisshush

    Speaking as someone who reads a lot on this topic this site has earned a high position in my source rankings, and a stop at findgrowthchannelsfast reinforced that ranking, the informal ranking of sources for a topic is something I maintain mentally and this site has moved into the upper portion of those rankings clearly.

    Reply
  30. EmilianoFah

    Useful read, especially because the writer did not assume too much background from the reader, and a quick look at growththroughclarity continued in the same way, a thoughtful site that meets people where they are which is something the modern web could use a lot more of for both casual and serious readers.

    Reply
  31. ReeseGuets

    Easily one of the better explanations I have read on the topic, and a stop at explorefreshdirectionalideas pushed it even higher in my mental ranking of useful resources, the kind of site that beats the average not by trying harder but by simply caring more about what it puts out daily which always shows.

    Reply
  32. LelandKaf

    Now realising the post has been quietly doing important work in my mind for the past hour, and a stop at parcelparadise extended that quiet processing, content that continues to do work after I close the tab is content with afterlife in the mind and this site is producing those long lived effects at a meaningful rate.

    Reply
  33. Chrislow

    Most blog writing on this subject reaches for the same handful of arguments and this post avoided them, and a look at unlocksmartideas continued the original treatment, content that finds its own path through territory other writers have flattened is content with real authorial energy and this site has plenty of that distinctive energy.

    Reply
  34. syvenirnaya prodykciya s logotipom_fsSl

    Народ, привет! Такая ситуация — на планерке сказали срочно найти подарки для клиентов. Присматриваюсь к подаркам с логотипом, но боюсь нарваться на кривую печать. сувениры с логотипом сувениры с логотипом А то эти менеджеры по рекламе такие цены выкатывают — волосы дыбом. Нужно штук 300-500, но если будет норм цена, можем и больше взять. А то я уже второй день в интернете сижу и ничего адекватного не нашёл.

    Reply
  35. Kak naiti cheloveka po nomery telefona_seoa

    Случайно наткнулся на один гайд, Знакомая многим фигня, потерял контакт со старым хорошим другом. Решил докопаться до истины и разобраться,. И знаете что? Тут главное знать, куда именно смотреть и какие базы юзать.

    Короче, если вас сейчас волнует тот же самый вопрос — быстро определить владельца номера, то есть один нормальный рабочий метод. Конкретно про то, где найти по телефонному номеру актуальные данные — вот здесь всё максимально норм расписано: найти телефон по номеру телефона найти телефон по номеру телефона.

    Я сам сначала вообще не верил во всё это. Потому что а тут выложена конкретная и структурированная информация. В общем, кому надо — тот точно воспользуется. Век живи — век учись, как говорится.

    Reply
  36. syvenirnaya prodykciya s logotipom_pdSl

    Народ, привет! Ох, уже голова болит с этим тимбилдингом, нужны нормальные презенты для партнеров. Может, кто шарит где лучше брать сувенирную продукцию с логотипом. корпоративная атрибутика корпоративная атрибутика А то эти менеджеры по рекламе такие цены выкатывают — волосы дыбом. Просили ещё брендированные кружки и толстовки. А то я уже второй день в интернете сижу и ничего адекватного не нашёл.

    Reply
  37. JaylenShage

    Liked the balance between depth and brevity, never too shallow and never too long, and a stop at designyourdirection kept the same balance going across the rest of the site, this is one of the harder skills in writing and the team here clearly has it figured out very well indeed across every page.

    Reply
  38. DillonTip

    Skipped the related products section because there was none, and a stop at learnandexecutenow also lacked any aggressive monetisation, content that is not constantly trying to convert me into a customer or subscriber is content that has confidence in its own value and that confidence shows up as a different reading experience.

    Reply
  39. CoreyRig

    Reading this confirmed that the topic deserves more careful attention than it usually gets, and a stop at unlocknewideas extended that elevated framing, content that raises the appropriate weight of a subject without being preachy about it is serving a quiet but important editorial function for the broader cultural conversation about it.

    Reply
  40. AbelHew

    Quietly the writers approach to the topic differs from the dominant takes I have been encountering, and a stop at buildsmartmovement extended that distinctive approach, content that maintains a different perspective without explicitly arguing against the dominant ones is content with confident editorial identity and this site has that confidence throughout pieces.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *