Laravel 8路由到控制器 SEO友好的URL结构

问题描述

我试图弄清楚如何在Laravel 8项目中实现特定的URL结构以及实现此目标的必要途径。我想要的是:

git push heroku master
Enumerating objects: 6962,done.
Counting objects: 100% (6962/6962),done.
Delta compression using up to 4 threads
Compressing objects: 100% (4022/4022),done.
Writing objects: 100% (6962/6962),15.05 MiB | 189.00 KiB/s,done.
Total 6962 (delta 1888),reused 6927 (delta 1865),pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.9.0
remote: -----> Installing pip 20.1.1,setuptools 47.1.1 and wheel 0.34.2
remote: -----> Installing sqlite3
remote: -----> Installing requirements with pip
remote:        Collecting asgiref==3.2.10
remote:          Downloading asgiref-3.2.10-py3-none-any.whl (19 kB)
remote:        Collecting dj-database-url==0.5.0
remote:          Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB)
remote:        Collecting dj-static==0.0.6
remote:          Downloading dj-static-0.0.6.tar.gz (3.4 kB)
remote:        Collecting Django==3.1.2
remote:          Downloading Django-3.1.2-py3-none-any.whl (7.8 MB)
remote:        Collecting django-bootstrap3==14.1.0
remote:          Downloading django_bootstrap3-14.1.0-py3-none-any.whl (23 kB)
remote:        Collecting gunicorn==20.0.4
remote:          Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB)
remote:        Collecting pytz==2020.1
remote:          Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB)
remote:        Collecting sqlparse==0.4.1
remote:          Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB)
remote:        Collecting static3==0.7.0
remote:          Downloading static3-0.7.0.tar.gz (24 kB)
remote:        Collecting whitenoise==5.2.0
remote:          Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB)
remote:        Building wheels for collected packages: dj-static,static3
remote:          Building wheel for dj-static (setup.py): started
remote:          Building wheel for dj-static (setup.py): finished with status 'done'
remote:          Created wheel for dj-static: filename=dj_static-0.0.6-py3-none-any.whl size=3051 
sha256=c8389fabbd7eda5b003f60986d0674c04ce2e162126ae3b87eb5059831f0d184
remote:          Stored in directory: /tmp/pip-ephem-wheel-cache- 
j02lo4pu/wheels/b5/10/4a/83f0c20117a4580af66c382f5cd1c689e6a8818a042ffdedd3
remote:          Building wheel for static3 (setup.py): started
remote:          Building wheel for static3 (setup.py): finished with status 'done'
remote:          Created wheel for static3: filename=static3-0.7.0-py3-none-any.whl size=18606 
sha256=5731bb65876d7b56b86eb47e33f4879111185ae7ab86e9d8d16cb5ecd036ba33
remote:          Stored in directory: /tmp/pip-ephem-wheel-cache- 
j02lo4pu/wheels/67/88/26/362b5f8314043c6241ed324b9f76ddf48328b775923b39590a
remote:        Successfully built dj-static static3
remote:        Installing collected packages: asgiref,dj-database-url,static3,dj-static,pytz,sqlparse,Django,django-bootstrap3,gunicorn,whitenoise
remote:        Successfully installed Django-3.1.2 asgiref-3.2.10 dj-database-url-0.5.0 dj-static- 
0.0.6 django-bootstrap3-14.1.0 gunicorn-20.0.4 pytz-2020.1 sqlparse-0.4.1 static3-0.7.0 whitenoise- 
5.2.0
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "/tmp/build_1d5fef1c/manage.py",line 22,in <module>
remote:            main()
remote:          File "/tmp/build_1d5fef1c/manage.py",line 18,in main
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.9/site- 
packages/django/core/management/__init__.py",line 401,in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.9/site- 
packages/django/core/management/__init__.py",line 345,in execute
remote:            settings.INSTALLED_APPS
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 
83,in __getattr__
remote:            self._setup(name)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 
70,in _setup
remote:            self._wrapped = Settings(settings_module)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 
177,in __init__
remote:            mod = importlib.import_module(self.SETTINGS_MODULE)
remote:          File "/app/.heroku/python/lib/python3.9/importlib/__init__.py",line 127,in 
import_module
remote:            return _bootstrap._gcd_import(name[level:],package,level)
remote:          File "<frozen importlib._bootstrap>",line 1030,in _gcd_import
remote:          File "<frozen importlib._bootstrap>",line 1007,in _find_and_load
remote:          File "<frozen importlib._bootstrap>",line 986,in _find_and_load_unlocked
remote:          File "<frozen importlib._bootstrap>",line 680,in _load_unlocked
remote:          File "<frozen importlib._bootstrap_external>",line 790,in exec_module
remote:          File "<frozen importlib._bootstrap>",line 228,in _call_with_frames_removed
remote:          File "/tmp/build_1d5fef1c/learning_log/settings.py",line 160,in <module>
remote:            BASE_DIR = os.path.dirname(os.path.adspath(__file__))
remote:        AttributeError: module 'posixpath' has no attribute 'adspath'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this error.
remote:        Or,you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set disABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected,Failed to compile Python app.
remote:
remote:  !     Push Failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to mynewapplog.
remote:
To https://git.heroku.com/mynewapplog.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: Failed to push some refs to 'https://git.heroku.com/mynewapplog.git'

这是因为我们不希望每个列表或博客文章的URL中包含字符串“目录”或“博客”。没有它,搜索引擎的效果会更好。

到目前为止,我在web.PHP路由文件底部使用了一个包罗万象的路由{any}来“捕获所有”达到目标的路由。然后,我操纵路径提供的字符串,以从网址末尾获取ID和单个字符标记。然后,我有了这两个变量,但可以弄清楚如何将它们传递给正确的控制器!

或者我真的很傻,有更好的方法来实现这一目标吗?

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# Security WARNING: keep the secret key used in production secret!
SECRET_KEY = '(*ru69!qi-6ei^kfnrw@^t_9_mnbttt$((bgx6%!10hz$iy$7z'

# Security WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = [
    'intense-depths-58584.herokuapp.com','127.0.0.1','localhost','admin','topic',]

# Application deFinition

INSTALLED_APPS = [
    'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# Third party apps.
     'bootstrap3',# My apps
    'learning_logs','users',]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware','whitenoise.middleware.WhiteNoiseMiddleware','django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]

ROOT_URLconf = 'learning_log.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [],'APP_Dirs': True,'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},]

Wsgi_APPLICATION = 'learning_log.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',}
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',{
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',{
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',{
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

# My setting (((((((this takes the place of the changes in views.py in the users file)))))))
logoUT_REDIRECT_URL = '/'

# My settings.
LOGIN_URL = '/users/login/'

# Settings for django-bootstrap3
BOOTSTRAP3 = {
    'include_jquery': True,}

# Heruko settings.
cwd = os.getcwd()
if cwd == '/app' or cwd[:4] == '/tmp':
    import dj_database_url

    DATABASES = {
        'default': dj_database_url.config(default='postgres://localhost')
    }

# Honor the 'X-Forwarded-Porto' header for request.is_secure().
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO','https')

# Allow all host readers.
    ALLOWED_HOSTS = ['*']

# Static asset configuration.
    BASE_DIR = os.path.dirname(os.path.adspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATICFILES_Dirs = (
        os.path.join(BASE_DIR,'static'),)

解决方法

我会将路径分为2个变量($slug$id),然后将其直接传递给控制器​​。

Route::get('{slug}-d{id}.html','DirectoryController@show')
    ->where(['slug' => '([a-z\-]+)','id' => '(\d+)']);

Route::get('{slug}-p{id}.html','PostController@show')
    ->where(['slug' => '([a-z\-]+)','id' => '(\d+)']);

在您的控制器中

class DirectoryController
{
    public function show(string $slug,int $id) {}
}

class PostController
{
    public function show(string $slug,int $id) {}
}
,

我可以看到两种实现此结果的方法:

创建一个中间控制器

Route::get('{path}','CheckPathController@redirect')

然后在CheckPathController中进行所有检查,并调用适当的控制器操作:

public function redirect(Request $request,$path) {
  // Your checks on $path,extract $id and content type

  if($isPost) {
     $controller = resolve(PostController::class);
     return $controller->show($request,$id);
  }

  if($isBusiness) {
     $controller = resolve(BusinessController::class);
     return $controller->show($request,$id);
  }

  // No matches,error 404
  abort(404);
}

复杂的正则表达式

请参阅:https://laravel.com/docs/8.x/routing#parameters-regular-expression-constraints

我不是正则表达式大师,这应该是可以匹配任何{word}-{word}-...-p{id}.html模式的基础,但是如果出现意外字符,它将崩溃

Route::get('{path}','PostController::show')
   ->where(['path' => '([\w]*-)*p[0-9]+\.html$']);

Route::get('{path}','BusinessController::show')
   ->where(['path' => '([\w]*-)*d[0-9]+\.html$']);

请注意,在这种情况下,您的控制器将收到拉$path字符串,因此您需要在其中提取ID。

,

您可以使用正则表达式匹配该子弹

Route::get('/{any}','YourController@methodName')->where(['any' => '.*(-d(.*?)\.).*']);

重复p

然后,当您使用控制器方法提取$ site时,可以使用正则表达式来获取该站点。

public function methodName($site)
{
    preg_match('/.*(-(d(.*?))\.).*/',$site,$parts); //or something similar,$parts[2] will have what you want
}

OR

这将为您的控制器方法提供d {number}或p {number}

Route::get('/{site}',function($site) {
    $code = preg_match('/.*(-(d(.*?)|p(.*?))\.).*/',$parts) ? $parts[2] : null;

    $controllerName = 'ControllerA';
    if(isset($code) && !is_null($code) && Str::contains($code,'p')) {
        $controllerName = 'ControllerB';
    }

    $controller = app()->make('App\Http\Controllers\Application\\' . $controllerName);

    return $controller->callAction('methodName',$params = ['code' => $code]);
})->where(['site' => '.*(-(d|p)(.*?)\.).*']);